Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl-style quotes for long strings in C++

Tags:

c++

perl

latex

Is there a way in C++ to quote a string without having to escape with backslashes? For example, I would like a way to store some Latex code in a string, such as \documentclass{article}. I could do

string latex_code = "\\documentclass{article}"

But that gets annoying when you have to escape a lot of things, for example if you have a lot of Latex code. In Perl, I remember that you have some very useful quoting tools. See, for example, the "q" and "qq" sections here: http://www.perlmonks.org/?node_id=401006

Is there something similar in C++? The only other thing I can think of is to paste the Latex code into an external file and read it in. But that also seems annoying.

like image 408
Xu Wang Avatar asked Jan 22 '12 04:01

Xu Wang


2 Answers

C++11 has a way:

R"(The String Data \ Stuff " )"
R"delimiter(The String Data \ Stuff " )delimiter"

In the first case, everything between the "( and the )" is part of the string. The " and \ characters do not need to be escaped. In the second case, the "delimiter( starts the string, and it only ends when )delimiter" is reached. The string delimiter can be any string up to 16 characters in length, including the empty string. This string cannot contain spaces, control characters, '(', ')', or the '\' character. The use of this delimiter string allows the user to have ")" characters within raw string literals. For example, R"delimiter((a-z))delimiter" is equivalent to "(a-z)"

http://en.wikipedia.org/wiki/C%2B%2B11

It's not possible in C++03.

like image 188
Pubby Avatar answered Nov 07 '22 21:11

Pubby


C++0x has several new string literals. One of them is the raw string literal which lets you use different delimiters for you strings. Raw strings start with an R character. A basic raw string literal would be R"(Hello, World!)". Here everything between "( and )" is part of the string.

You can also specify different delimiters by putting some string in between the " and ( characters. For example the raw string R"delimiter(Hello, World!)delimiter" is the same string as above except it uses "delimiter( as the delimiter. The delimiter part can be up to 16 characters and cannot contain spaces, (, ) or / characters.

Since this is a C++0x feature it requires a C++0x compatible compiler. It seems that gcc has supported this feature since version 4.5 and clang has since version 3.0.

like image 37
David Brown Avatar answered Nov 07 '22 21:11

David Brown