Dracep
Dracep

Reputation: 378

Printing variable in quotation marks C++

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

Answers (4)

NathanOliver
NathanOliver

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

Stephan Lechner
Stephan Lechner

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

shb
shb

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

Brandon Lyons
Brandon Lyons

Reputation: 463

string element = "\"hello\"";
std::cout << element;

Upvotes: 2

Related Questions