Reputation: 378
given:
string element = "hello";
I would like to have the following printed:
"hello" //with quotation marks
I found how to print words with quotation marks using \"hello\", but I would like to use my variable name element to print out "hello".
Upvotes: 3
Views: 8286
Reputation: 180500
The closest you can get to have
string element = "hello";
std::cout << element
and have it print
"hello"
is to use std::quoted
That would make the code
string element = "hello";
std::cout << std::quoted(element);
and it would output
"hello"
Do note that std::quoted
does more then just add the out quotes. If your string contains quotes then it will modify those and add a \
in from of them. That means
string element = "hello \"there\" bob";
std::cout << std::quoted(element);
will print
"hello \"there\" bob"
instead of
"hello "there" bob"
Upvotes: 15
Reputation: 35154
You'll have to write the quotation marks and the variable extra, like
std::cout << '\"' << element << '\"';
BTW: in contrast to a string literal like "\""
, where you have to escape double quotes, by using a character literal, you can get away without escaping: So the following is valid as well:
std::cout << '"' << element << '"';
Upvotes: 6
Reputation: 6277
use forward slash in front of quotation marks
std::cout << "\"" << element << "\"" << std::endl;
if you want to have quotation mark inside your string, assign the variable with quotation mark with forward slash
string element = "\"hello\"";
Upvotes: 6