使用一个 cout 命令打印多个字符串,每个字符串放在不同的(文本编辑器)行
Using one cout command to print multiple strings with each string placed on a different (text editor) line
看看下面的例子:
cout << "option 1:
\n option 2:
\n option 3";
我知道,这不是输出字符串的最佳方式,但问题是为什么这会导致错误提示“字符丢失?有一个字符串必须转到 stdout,但它只包含很多空白字符。
这个怎么样:
string x="
string_test";
人们可能将该字符串解释为:“\nxxxxxxxxxxxxstring_test”,其中 x 是一个空白字符。
这是惯例吗?
那叫multiline string literal
。
您需要对嵌入的换行符进行转义。否则编译不通过:
std::cout << "Hello world \
and Whosebug";
注意:反斜杠必须紧接在行结束之前,因为它们需要转义源代码中的换行符。
您还可以利用有趣的事实 "Adjacent string literals are concatenated by the compiler"
来获得优势:
std::cout << "Hello World"
"Stack overflow";
参见 this for raw string literals
. In C++11, we have raw string literals
. They are kind of like here-text。
语法:
prefix(optional) R"delimiter( raw_characters )delimiter"
It allows any character sequence, except that it must not contain the
closing sequence )delimiter"
. It is used to avoid escaping of any
character. Anything between the delimiters becomes part of the string.
const char* s1 = R"foo(
Hello
World
)foo";
示例取自 cppreference。
看看下面的例子:
cout << "option 1:
\n option 2:
\n option 3";
我知道,这不是输出字符串的最佳方式,但问题是为什么这会导致错误提示“字符丢失?有一个字符串必须转到 stdout,但它只包含很多空白字符。
这个怎么样:
string x="
string_test";
人们可能将该字符串解释为:“\nxxxxxxxxxxxxstring_test”,其中 x 是一个空白字符。
这是惯例吗?
那叫multiline string literal
。
您需要对嵌入的换行符进行转义。否则编译不通过:
std::cout << "Hello world \
and Whosebug";
注意:反斜杠必须紧接在行结束之前,因为它们需要转义源代码中的换行符。
您还可以利用有趣的事实 "Adjacent string literals are concatenated by the compiler"
来获得优势:
std::cout << "Hello World"
"Stack overflow";
参见 this for raw string literals
. In C++11, we have raw string literals
. They are kind of like here-text。
语法:
prefix(optional) R"delimiter( raw_characters )delimiter"
It allows any character sequence, except that it must not contain the closing sequence
)delimiter"
. It is used to avoid escaping of any character. Anything between the delimiters becomes part of the string.
const char* s1 = R"foo(
Hello
World
)foo";
示例取自 cppreference。