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


当前回答

嗯…排序的。最简单的方法是使用相邻的字符串字面值由编译器连接的事实:

const char *text =
  "This text is pretty long, but will be "
  "concatenated into just a single string. "
  "The disadvantage is that you have to quote "
  "each part, and newlines must be literal as "
  "usual.";

缩进并不重要,因为它不在引号内。

你也可以这样做,只要你注意转义嵌入的换行符。如果不这样做,就像我的第一个答案一样,将无法编译:

const char *text2 =
  "Here, on the other hand, I've gone crazy \
and really let the literal span several lines, \
without bothering with quoting each line's \
content. This works, but you can't indent.";

同样,注意每行末尾的反斜杠,它们必须在行结束之前,它们在源文件中转义换行符,这样就好像换行符不存在一样。你不会在有反斜杠的位置得到换行符。使用这种形式,您显然不能缩进文本,因为缩进将成为字符串的一部分,用随机空格混淆它。

其他回答

你还可以这样做:

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

你可以这样做:

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

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

为了在@unwind的回答中稍微说明一下@emsr的注释,如果一个人不够幸运,没有c++ 11编译器(比如GCC 4.2.1),并且他想在字符串中嵌入换行符(char *或类字符串),他可以这样写:

const char *text =
  "This text is pretty long, but will be\n"
  "concatenated into just a single string.\n"
  "The disadvantage is that you have to quote\n"
  "each part, and newlines must be literal as\n"
  "usual.";

很明显,这是真的,但是@emsr的简短评论在我第一次读到这篇文章时并没有跳入我的脑海,所以我必须自己去发现。希望我为其他人节省了几分钟时间。

嗯…排序的。最简单的方法是使用相邻的字符串字面值由编译器连接的事实:

const char *text =
  "This text is pretty long, but will be "
  "concatenated into just a single string. "
  "The disadvantage is that you have to quote "
  "each part, and newlines must be literal as "
  "usual.";

缩进并不重要,因为它不在引号内。

你也可以这样做,只要你注意转义嵌入的换行符。如果不这样做,就像我的第一个答案一样,将无法编译:

const char *text2 =
  "Here, on the other hand, I've gone crazy \
and really let the literal span several lines, \
without bothering with quoting each line's \
content. This works, but you can't indent.";

同样,注意每行末尾的反斜杠,它们必须在行结束之前,它们在源文件中转义换行符,这样就好像换行符不存在一样。你不会在有反斜杠的位置得到换行符。使用这种形式,您显然不能缩进文本,因为缩进将成为字符串的一部分,用随机空格混淆它。