C ++多行字符串文字 [英] C++ multiline string literal

查看:149
本文介绍了C ++多行字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以有多行纯文本,在C + +,Perl的常量文字?也许一些解析技巧与 #include 一个文件?我不能想到一个,但男孩,这将是很好。我知道它会在C ++ 0x。

Is there any way to have multi-line plain-text, constant literals in C++, à la Perl? Maybe some parsing trick with #includeing a file? I can't think of one, but boy, that would be nice. I know it'll be in C++0x.

推荐答案

最简单的是使用相邻字符串字符串由编译器连接的事实:

Well ... Sort of. The easiest is to just use the fact that adjacent string literals are concatenated by the compiler:

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

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

The indentation doesn't matter, since it's not inside the quotes.

你也可以这样做,只要你小心的逃避嵌入的换行符。没有这样做,像我的第一个答案,不会编译:

You can also do this, as long as you take care to escape the embedded newline. Failure to do so, like my first answer did, will not compile:


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

再次注意,每行结尾处的反斜杠,它们必须紧接在行结束之前,它们将转义为换行符源,使其成为字符串字面量的一部分。使用此表单,您不能缩进文本,因为缩进将成为字符串的一部分,用随机空格加粗。

Again, note those backslashes at the end of each line, they must be immediately before the line ends, they are escaping the newline in the source, making it part of the string literal. With this form, you can't indent the text since the indentation would then become part of the string, garbling it with random spaces.

这篇关于C ++多行字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆