有没有办法有多行纯文本,常量字面量在c++, à la Perl?也许是使用#include文件的一些解析技巧?我想不出一个,但那太好了。我知道是c++ 0x。


当前回答

你可以这样做:

const char *text = "This is my string it is "
     "very long";

其他回答

// C++11. 
std::string index_html=R"html(
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>VIPSDK MONITOR</title>
    <meta http-equiv="refresh" content="10">
</head>
<style type="text/css">
</style>
</html>
)html";

你还可以这样做:

const char *longString = R""""(
This is 
a very 
long 
string
)"""";

由于一盎司的经验胜过一吨的理论,我尝试了一个关于MULTILINE的小测试程序:

#define MULTILINE(...) #__VA_ARGS__

const char *mstr[] =
{
    MULTILINE(1, 2, 3),       // "1, 2, 3"
    MULTILINE(1,2,3),         // "1,2,3"
    MULTILINE(1 , 2 , 3),     // "1 , 2 , 3"
    MULTILINE( 1 , 2 , 3 ),   // "1 , 2 , 3"
    MULTILINE((1,  2,  3)),   // "(1,  2,  3)"
    MULTILINE(1
              2
              3),             // "1 2 3"
    MULTILINE(1\n2\n3\n),     // "1\n2\n3\n"
    MULTILINE(1\n
              2\n
              3\n),           // "1\n 2\n 3\n"
    MULTILINE(1, "2" \3)      // "1, \"2\" \3"
};

用cpp -P -std=c++11的文件名来编译这个片段。

#__VA_ARGS__背后的技巧是__VA_ARGS__不处理逗号分隔符。你可以把它传递给字符串化操作符。开头和结尾的空格被修剪,单词之间的空格(包括换行)被压缩为一个空格。括号需要平衡。我认为这些缺点解释了为什么c++ 11的设计者,尽管有#__VA_ARGS__,看到了原始字符串字面量的需求。

你可以这样做:

const char *text = "This is my string it is "
     "very long";

#定义MULTILINE(…)#__VA_ARGS__ 消耗括号之间的所有东西。 将任意数量的连续空白字符替换为单个空格。