C++ 多行字符串原始文字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20508534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:10:43  来源:igfitidea点击:

C++ multiline string raw literal

c++

提问by Gisway

We can define a string with multiline like this:

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

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

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

How about with raw literal, I tried all, no one works

原始文字怎么样,我尝试了所有,没有人工作

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";

回答by Michael Burr

Note that raw string literals are delimited by R"(and )"(or you can add to the delimiter by adding characters between the quote and the parens if you need additional 'uniqueness').

请注意,原始字符串文字由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;
}

回答by chris

Just write it as you want it:

随心所欲地写:

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

The other thing you didn't put in was the required pair of parentheses around the entire string.

您没有输入的另一件事是在整个字符串周围需要一对括号。

Also keep in mind any leading spaces on the part 2-4 lines that you might put in to keep the code formatted are included, as well as a leading newline to get part 1 with the others, so it does make it rather ugly to see in the code sometimes.

还要记住,第 2-4 行上的任何前导空格都包括在内,您可能会为了保持代码格式而放入其中,以及一个前导换行符,以便将第 1 部分与其他行一起获取,因此它确实让人很难看有时在代码中。

An option that might be plausible for keeping things tidy, but still using raw string literals is to concatenate newlines:

为了保持整洁,但仍然使用原始字符串文字可能是合理的一个选项是连接换行符:

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