我正在用C ++编写一个cout
语句,但是该语句非常大,所以我按Enter键以便可以从下一行开始(不想在一行中写完整的长语句)。它工作正常,但是如果\n
(换行)是按回车键后的第一个字符,因为您可以看到第二行代码则不起作用。因此,我只想问问在按Enter键后,有什么方法可以从下一行(继续上一行代码)开始您的代码。
cout<<"\nChoose the operation you want to perform :
\n1. To insert a node in the BST and in the tree \n2";
答案 0 :(得分:1)
是的,您可以这样:
std::cout << "\nChoose the operation you want to perform:\n"
"1. To insert a node in the BST and in the tree\n"
"2. ...\n";
您不能在一行中没有以"
结尾的字符串,而是将一行中两个正确终止的字符串连接在一起。因此"foo" "bar"
成为"foobar"
。在单独的行上放置"foo"
和"bar"
很好。
正如其他人提到的那样,C ++ 11支持原始字符串文字,它确实允许将字符串分散在多行中,并且避免了必须编写\n
:
std::cout << R"(
Choose the operation you want to perform:
1. To insert a node in the BST and in the tree
2. ...
)";
答案 1 :(得分:0)
您可以使用多行字符串文字,例如
const char* s1 = "\nChoose the operation you want to perform:\n"
"1. To insert a node in the BST and in the tree\n"
"2. some text here";
您可以使用不带引号或换行符的原始字符串文字(例如,在cppreference.com,例如string literals):
const char* s1 = R"foo(
Choose the operation you want to perform:
1. To insert a node in the BST and in the tree
2. some text here)foo";
这两个s1
变量是等效的。然后写
std::cout << s1;
答案 2 :(得分:0)
您可以选择:
std::cout << "\nSome text,\n"
"\nsomething else\n";
(最初由@G。Sliepen提出)
我宁愿使用std::endl
。
代码如下:
std::cout << std::endl << "Some text," << std::endl <<
std::endl << "something else" << std::endl;
另一种选择是使用R
prefix(用于避免转义任何字符):
std::cout << R"(
Some text,
something else
)";
我的最爱是最后一个。