How to output verbatim strings in C++ - c++

Suppose I need to output some program code from my C++ code. So I need to print things like:
cout << "foo(\"hello\", \"world\", 5)" << endl;
Is there a way so that I do not need to escape each " ?

With C++11 you can do
R"delimeter(foo("hello", "world",5))delimeter"
Where R"delimeter( defines the start of a raw string, delimeter is a label up to 16 characters, and )delimeter" ends the raw string.

If you're using C++03, you can use a Macro to do what you want:
#define PRINT_STRING(s) cout << (#s) << endl;
int main() {
cout << "foo(\"hello\", \"world\", 5)" << endl;
PRINT_STRING(foo("hello", "world", 5))
return 0;
}
Returns
output:
foo("hello", "world", 5)
foo("hello", "world", 5)
You can see it here: http://ideone.com/G6TvU3

If your compiler supports C++11 the multiline quote construct is R"LABEL( Where LABEL is a valid label. To end the quote use )LABEL"

Related

What is the difference between these two C++ statements to concatenate a string?

I'm new to C++ and I was wondering what the difference is between these two lines:
cout << "John " << "Doe" << endl;
cout << "John " + "Doe" << endl;
The first one works but the second one doesn't. Any ideas?
The first line
cout << "John " << "Doe" << endl;
doesn't concatenate strings. It prints "John " and then it prints "Doe". But there never existed a string "John Doe".
The second line
cout << "John " + "Doe" << endl;
is syntactically wrong. There is no operator+ overloaded for char arrays.
To concatenate string literals you can use
#include <iostream>
#include <string>
using std::literals::string_literals::operator""s;
int main() {
std::cout << "John "s + "Doe"s << std::endl;
// or
auto name = "John "s + "Doe"s;
std::cout << name << std::endl;
}
since C++14. operator""s creates a std::string with operator+.
The second expression is evaluated as
cout << ("John " + "Doe") << endl;
due to the language grammar (often thought of as operator precedence).
But "John " is a const char[6] type and "Doe" is const char[4] type. Due to the +, both decay to a const char* pointer. And pointers cannot be added, so the compiler issues a diagnostic.
In the first case, the overload << on std::ostream for a const char* is used twice, with the results you expect.
First one inserts "John " into the standard output, and then it inserts "Doe". End result is that you see both strings in a sequence.
The second attempts to use the addition operator with arrays as operands. This is ill-formed because such operator does not exist in C++.
For starters there is no concatenation of strings.
In the first statement
cout << "John " << "Doe" << endl;
there are outputted sequentially two strings.
In the second statement
cout << "John " + "Doe" << endl;
there is an attempt to perform the binary operation + with two pointers of the type const char * to which the used string literals having array types are implicitly converted. However the operator + is not defined for pointers.
You may use the operator - for pointers like
std::cout << "John " - "Doe" << std::endl;
This statement syntactically correct but semantically has undefined behavior because the pointers do not point to elements of the same array.
Built-in array types do not have the binary operator +.
This operator is overloaded for the user-defined class template std::basic_string.
You could write for example
#include <iostream>
#include <string>
int main()
{
std::cout << std::string( "John " ) + "Doe" << std::endl;
return 0;
}
Or you could use a user-defined string literal like
#include <iostream>
#include <string>
int main()
{
using namespace std::string_literals;
std::cout << "John "s + "Doe" << std::endl;
return 0;
}
Or in the C++ 17 Standard there is defined new class template std::string_view that you also could use to concatenate strings.
To concatenate two literal strings, just write one after the other with no intervening characters other than whitespace:
const char *lit = "John " "Doe";
std::cout << lit << '\n';
or
std::cout << "John "
"Doe";
etc.
The reason the second one does not work is that you can't concatenate two string literals with + operator. On the other hand, the first approach utilizes chaining of insertion operators to print multiple expressions
The first method is the correct method to concatenate two strings in C++. Whereas the second method, is by default the method to concatenate two strings in Python.
You can't use the second as it is not supported as it indicates addition of two strings and not concatenation (as seen by c++ compiler).
String literals like "foo" cannot be added (i.e. operator+) together for concatenation like in many other languages. This is reasonable in a low-level language like C++ because (in the general case) that would mean an allocation would have to take place.
However, if you are fine with that, then you can use std::string objects which do have those facilities for you. The following works:
cout << string("John ") + string("Doe") << endl;

How would I print quotation marks in the output in C++? [duplicate]

This question already has answers here:
Printing variable in quotation marks C++
(4 answers)
how to declare char * with input of {"data": "0001"}'
(1 answer)
Closed 4 years ago.
I am beginning my C++ coding with challenges from the book Exercises for Programmers by Brian P.Hogan. I am capable of doing this, it's just I have never come across this int he 4 weeks I have been coding.
I am attempting to write a simple program that prompts the user for a quote, and the author of the quote.
Code:
#include <iostream>
#include <cstring>
int main(int argc, char const *argv[])
{
std::string quote;
std::string author;
std::cout << "Please enter a quote" << '\n';
std::cin >> quote;
std::cout << "Please enter the author" << '\n';
std::cin >> author;
std::cout << author << " said " << ""quote"" << '\n';
return 0;
}
Output:
compile error
With the above code, it compiles wrong. This is because of the double quotation marks
std::cout << author << " said " << ""quote"" << '\n';
The desired output will look something like this
What is the quote? These aren't the droids you're looking for.
Who said it? Obi-Wan Kenobi
Obi-Wan Kenobi says, "These aren't the droids
you're looking for."
Notice the quotation marks on the desired output around the quote (how a quote should really look anyway). I have looked online, but haven't been able to find a solution specifically for C++.
What I am asking, is how do i display text in the terminal with quotation marks around it. (Like this - "hello")
I hope you understand the question. It is my first post and I tried to make it as clear as possible what the issue is.
Thanks in advance.
escape the quote:
https://ideone.com/lcrYlA
#include <iostream>
int main()
{
// your code goes here
std::cout << " hello " << " \"world\"" << std::endl;
return 0;
}
You can of course do:
std::cout << author << " said \" "<< quote << "\"\n";
Quote the quote with \
std::cout << "the character \" is a quote";
You can escape the string using a backslash \" e.g printf("Quotes \"\" ");

can I Remove "endl" in ( cout<<" "<<endl ) in C++?

I am beginner at C++, my question is can I remove endl the one at the end of cout like :
cout<<" "<<endl;
I don't want return to new line . If I can't remove it, what should I do?
Elephant in the room: remove the endl from the cout.
But in case you don't own that code, you could try "\033[F", which, if your terminal supports it, moves you to the previous line.
Another possibility would be to redirect the cout buffer using rdbuf to an ostream that you control. You could (i) redirect, (ii) call the function that writes the errant cout with the new line and (iii) inspect your ostream and write to the original buffer, this time omitting the endl. Switch everything back once you're done.
Yes of course you do not need to use std::endl every time you use <<. As an example a simple way to print a vector with spaces between the elements would look like:
std::vector<int> foo = {1,2,3,4,5};
for (auto e : foo)
std::cout << e << " ";
Here we never use a endl. You cout also just use \n at the end of a string literal and that will put a newline in the buffer as well.
std::cout << "test\n";
std::cout << "this will be on a new line";
Notice that I don't put a newline in the last cout<< so if there is anymore output it will start off right after the "e" in "line".
Yes you can remove endl. It is an optional parameter to the << stream operator of which there are many. If you don't include it then a new Carriage Return/Line Feed character will not be output and therefore text will appear on the same line in the output (presumably console).
For example
cout << "Hello, World" << endl;
would become:
cout << "Hello, World";
or to make the point another way you could write:
cout << "Hello,";
cout << " World";
There are lots of other examples out there too, here's one for starters: http://www.cplusplus.com/doc/tutorial/basic_io/
cout<<"Your message here.";
It's as simple as that. Were you trying to do something like...
cout<<"Your message here."<<; ....? This is wrong as:
The << operator signifies that something comes after the "" part. You don't have any in this case.

Right Justifying output stream in C++

I'm working in C++. I'm given a 10 digit string (char array) that may or may not have 3 dashes in it (making it up to 13 characters). Is there a built in way with the stream to right justify it?
How would I go about printing to the stream right justified? Is there a built in function/way to do this, or do I need to pad 3 spaces into the beginning of the character array?
I'm dealing with ostream to be specific, not sure if that matters.
You need to use std::setw in conjunction with std::right.
#include <iostream>
#include <iomanip>
int main(void)
{
std::cout << std::right << std::setw(13) << "foobar" << std::endl;
return 0;
}
Yes. You can use setw() to set the width. The default justification is right-justified, and the default padding is space, so this will add spaces to the left.
stream << setw(13) << yourString
See: setw(). You'll need to include <iomanip>.
See "setw" and "right" in your favorite C++ (iostream) reference for further details:
cout << setw(13) << right << your_string;
Not a unique answer, but an additional "gotcha" that I discovered and is too long for a comment...
All the formatting stuff is only applied once to yourString. Anything additional, like << yourString2 doesn't abide by the same formatting rules. For instance if I want to right-justify two strings and pad 24 asterisks (easier to see) to the left, this doesn't work:
std::ostringstream oss;
std::string h = "hello ";
std::string t = "there";
oss << std::right << std::setw(24) << h << t;
std::cout << oss.str() << std::endl;
// this outputs
******************hello there
That will apply the correct padding to "hello " only (that's 18 asterisks, making the entire width including the trailing space 24 long), and then "there" gets tacked on at the end, making the end result longer than I wanted. Instead, I wanted
*************hello there
Not sure if there's another way (you could simply redo the formatting I'm sure), but I found it easiest to simply combine the two strings into one:
std::ostringstream oss;
std::string h = "hello ";
std::string t = "there";
// + concatenates t onto h, creating one string
oss << std::right << std::setw(24) << h + t;
std::cout << oss.str() << std::endl;
// this outputs
*************hello there
The whole output is 24 long like I wanted.
Demonstration

boost regex sub-string match

I want to return output "match" if the pattern "regular" is a sub-string of variable st. Is this possible?
int main()
{
string st = "some regular expressions are Regxyzr";
boost::regex ex("[Rr]egular");
if (boost::regex_match(st, ex))
{
cout << "match" << endl;
}
else
{
cout << "not match" << endl;
}
}
The boost::regex_match only matches the whole string, you probably want boost::regex_search instead.
regex_search does what you want; regex_match is documented as
determines whether a given regular
expression matches all of a given
character sequence
(the emphasis is in the original URL I'm quoting from).
Your question is answered with example in library documentation - boost::regex
Alternate approach:
You can use boost::regex_iterator, this is useful for parsing file etc.
string[0],
string[1]
below indicates start and end iterator.
Ex:
boost::regex_iterator stIter(string[0], string[end], regExpression)
boost::regex_iterator endIter
for (stIter; stIter != endIter; ++stIter)
{
cout << " Whole string " << (*stIter)[0] << endl;
cout << " First sub-group " << (*stIter)[1] << endl;
}
}