C++多行字符串原始字面量

27

我们可以像这样定义一个多行字符串:

const char* text1 = "part 1"
                    "part 2"
                    "part 3"
                    "part 4";

const char* text2 = "part 1\
                     part 2\
                     part 3\
                     part 4";

使用原始字面量如何?我尝试了所有方法,但都不起作用。

std::string text1 = R"part 1"+
                    R"part 2"+ 
                    R"part 3"+
                    R"part 4";

std::string text2 = R"part 1"
                    R"part 2" 
                    R"part 3"
                    R"part 4";

std::string text3 = R"part 1\
                      part 2\ 
                      part 3\
                      part 4";

std::string text4 = R"part 1
                      part 2 
                      part 3
                      part 4";

2
“no one works” 是什么意思?你收到错误消息了吗? - Robert Harvey
请注意,您正在连接字符串而不插入换行符。 - Thomas Matthews
2
这些不是多行字符串 - 而是写在多行的字符串。 - Luchian Grigore
我的字符串太长了,我想把它们定义在多行中,这样在代码中阅读起来更容易。 - diwatu
@ThomasMatthews 2.14.5/1: “具有前缀'R'的字符串字面量是'原始字符串字面量'。”(例如R"**(\n)**")13.5.8/4:“'原始字面值运算符'是具有单参数类型为'const char *'的字面值运算符。 (例如MyClass operator "" _foo(const char*);)这两个短语是标准中涉及“原始”的唯一技术定义。 - aschepler
显示剩余7条评论
2个回答

44

按照您想要的方式书写:

std::string text = R"(part 1
part 2
part 3
part 4)";

你没有在整个字符串周围加上所需的一对括号。

还要记住,您可能会添加到 2-4 行的前导空格以保持代码格式的任何内容都包含在内,以及一个前导换行符来获取其他部分的第 1 部分,因此有时在代码中看起来相当丑陋。

一个可能合理的选择是保持整洁,但仍然使用原始字符串字面量,并连接换行符:

R"(part 1)" "\n" 
R"(part 2)" "\n" 
R"(part 3)" "\n" 
R"(part 4)"

我想将一个长字符串分割成不包含“\n”的单独代码行可能会很有用,特别是在处理复杂的正则表达式时。但是你的答案会向字符串中添加换行符,这可能不是预期的结果。 - Nikolai K.
@NikolaiK.,公平地说,虽然已经过了几年,但我可能认为嵌入的换行符是需要的。第二部分可以很容易地适应,以从结果中删除换行符。 - chris
谢谢。需要很高的智商才能强制混合原始字符串和常规字符串。 - user13947194

44

请注意,原始字符串字面量由 R"()" 包围(如果您需要额外的'独特性',可以在引号和括号之间添加字符以增加分隔符)。

#include <iostream>
#include <ostream>
#include <string>

int main () 
{
    // raw-string literal example with the literal made up of separate, concatenated literals
    std::string s = R"(abc)" 
                    R"( followed by not a newline: \n)"
                    " which is then followed by a non-raw literal that's concatenated \n with"
                    " an embedded non-raw newline";

    std::cout << s << std::endl;

    return 0;
}

1
谢谢你的回答。是R"(应该是R("吗?我现在不在电脑旁,无法尝试。 - diwatu
7
@Giswin,不,括号应该放在引号内。或许类似ideone或Coliru之类的工具仍然可以在你的手机上使用(或者你正在使用的设备)。 - chris
@Giswin:这个代码示例是一个小而完整的程序,它是从一个使用VS 2013和GCC 4.8.0编译和运行的文件中复制/粘贴而来的。因此,希望里面没有拼写错误。 - Michael Burr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接