How to write a string literal which contains double quotes [duplicate]
Asked Answered
S

4

14

I need to do the following C# code in C++ (if possible). I have to initialize a long string with lots of quotes and other stuff in it.

// C# verbatim string
const String _literal = @"I can use "quotes" inside here";
Sanmiguel answered 8/4, 2010 at 3:2 Comment(1)
Why not load such a long string from file?Announcer
M
35

That is not available in C++03 (the current standard).

That is part of the C++0x draft standard but that's not readily available just yet.

For now, you just have to quote it explicitly:

const std::string _literal = "I have to escape my quotes in \"C++03\"";

Once C++0x becomes reality, you'll be able to write:

const std::string _literal = R"(but "C++0x" has raw string literals)";

and when you need )" in your literal:

const std::string _literal = R"DELIM(more "(raw string)" fun)DELIM";
Merrymaking answered 8/4, 2010 at 3:4 Comment(1)
@paxdiablo - you're welcome. On a side note, my earlier example was incorrect. Raw strings use parentheses, not square bracket as delimiters. Also raw strings have more flexibility then my example shows (you can add a delimiter so that you can put )" in the actual string.Merrymaking
E
7

There is no equivalent of C#'s "@" in C++. The only way to achieve it is to escape the string properly:

const char *_literal = "I can use \"quotes\" inside here";
Earnestineearnings answered 8/4, 2010 at 3:3 Comment(0)
T
5

There is no raw string literals in C++. You'll need to escape your string literals.

std::string str = "I can use \"quotes\" inside here";

C++0x offers a raw string literal when it's available:

R"C:\mypath"

By the way you should not name anything with a leading underscore as such identifiers are reserved in C++.

Tarantula answered 8/4, 2010 at 3:2 Comment(2)
Names beginning with an underscore and then followed by a capital letter are reserved for the implementation for any use, so you can't use them at all. Names beginning with an underscore in general are only reserved as names in the global namespace.Jadejaded
@Brian - raw strings use parentheses R"(C:\mypath)"Merrymaking
N
2

There is no such mechanism in C++. You'll have to do it the old fashioned way, by using escapes.

You might be able to use a scripting language to make the escaping part a little easier, though. For instance, the %Q operator in Ruby will return a properly escaped double-quoted string when used in irb:

irb(main):003:0> %Q{hello "world" and stuff     with    tabs}
=> "hello \"world\" and stuff\twith\ttabs"
Neuroglia answered 8/4, 2010 at 3:2 Comment(2)
are you seriously suggesting embedding a Ruby interpreter in your C++ program just to escape a string?Subjective
@jalf: Absolutely not! I was suggesting to paste the string into Ruby once, then paste that result back into his source file. I can see where my answer could be interpreted in that ridiculous manner, though.Neuroglia

© 2022 - 2024 — McMap. All rights reserved.