如何将源代码中的长字符串拆分为多行以提高 C++ 的可读性?
How can I split a long string in source code into several lines for more readability in C++?
换句话说,如果我不想写一行,如何让我的代码工作?
#include <string>
using namespace std;
int main()
{
string menu = "";
menu += "MENU:\n"
+ "1. option 1\n"
+ "2. option 2\n"
+ "3. option 3\n"
+ "4. 10 more options\n";
}
您不需要 +
。通过将它们排除在外,编译器会将所有字符串文字连接成一个长字符串:
menu += "MENU:\n"
"1. option 1\n"
"2. option 2\n"
"3. option 3\n"
"4. 10 more options\n";
只需删除 +
的:
#include <string>
int main()
{
std::string menu = "MENU:\n"
"1. option 1\n"
"2. option 2\n"
"3. option 3\n"
"4. 10 more options\n";
}
相邻的字符串文字是 automatically concatenated by the compiler。
或者,在 C++11 中,您可以使用原始字符串文字,它保留所有缩进和换行符:
#include <string>
int main()
{
std::string menu = R"(MENU:
1. option 1
2. option 2
3. option 3
4. 10 more options
)";
}
只需删除示例中的添加运算符。中间没有任何内容的连续字符串被简单地连接起来。因此,例如,两个连续的标记 "hello " "world"
与 "hello world"
相同。但请记住,源代码换行符可以分隔任意两个标记,因此 "hello "
和 "world"
可以在不同的行上,如您所愿。
换句话说,如果我不想写一行,如何让我的代码工作?
#include <string>
using namespace std;
int main()
{
string menu = "";
menu += "MENU:\n"
+ "1. option 1\n"
+ "2. option 2\n"
+ "3. option 3\n"
+ "4. 10 more options\n";
}
您不需要 +
。通过将它们排除在外,编译器会将所有字符串文字连接成一个长字符串:
menu += "MENU:\n"
"1. option 1\n"
"2. option 2\n"
"3. option 3\n"
"4. 10 more options\n";
只需删除 +
的:
#include <string>
int main()
{
std::string menu = "MENU:\n"
"1. option 1\n"
"2. option 2\n"
"3. option 3\n"
"4. 10 more options\n";
}
相邻的字符串文字是 automatically concatenated by the compiler。
或者,在 C++11 中,您可以使用原始字符串文字,它保留所有缩进和换行符:
#include <string>
int main()
{
std::string menu = R"(MENU:
1. option 1
2. option 2
3. option 3
4. 10 more options
)";
}
只需删除示例中的添加运算符。中间没有任何内容的连续字符串被简单地连接起来。因此,例如,两个连续的标记 "hello " "world"
与 "hello world"
相同。但请记住,源代码换行符可以分隔任意两个标记,因此 "hello "
和 "world"
可以在不同的行上,如您所愿。