在 C 中创建多行字符串文字
这篇文章将讨论如何在 C++ 中创建多行字符串文字。
1. 使用字符串文字
C++ 提供隐式字符串连接,如果两个或多个字符串文字相邻,编译器会将它们连接在一起。这种隐式连接可用于在 C++ 中创建多行字符串文字,如下所示:
#include <iostream> #include <string> int main() { std::string multiline_str = "The journey " "of a thousand miles " "begins with one step."; std::cout << multiline_str << std::endl; return 0; }
输出:
The journey of a thousand miles begins with one step.
2.使用反斜杠
如果我们在每一行的末尾放置一个反斜杠,编译器就会删除换行符和前面的反斜杠字符。这形成了多行字符串。与以前的方法不同,缩进在这里很重要。
#include <iostream> #include <string> int main() { std::string multiline_str = "The journey \ of a thousand miles \ begins with one step."; std::cout << multiline_str << std::endl; return 0; }
输出:
The journey of a thousand miles begins with one step.
3. 使用原始字符串文字
形成多行字符串文字的最佳选择是使用原始字符串文字。此解决方案简洁而优雅,但仅适用于 C++11。请注意,字符串中的所有空格、换行符、缩进都会被保留。
#include <iostream> #include <string> int main() { std::string multiline_str = R"(The journey of a thousand miles begins with one step.)"; std::cout << multiline_str << std::endl; return 0; }
输出:
The journey
of a thousand miles
begins with one step.
4. 使用宏
最后,我们可以使用宏在 C++ 中创建多行字符串。缩进在这里无关紧要,解决方案将多个连续的空白字符替换为单个空格。
#include <iostream> #include <string> #define MULTILINE_STRING(...) #__VA_ARGS__ int main() { std::string multiline_str = MULTILINE_STRING(The journey of a thousand miles begins with one step.); std::cout << multiline_str << std::endl; return 0; }
输出:
The journey of a thousand miles begins with one step.
或在下面使用:
#include <iostream> #include <string> #define MULTILINE_STRING(s) #s int main() { std::string multiline_str = MULTILINE_STRING(The journey of a thousand miles begins with one step.); std::cout << multiline_str << std::endl; return 0; }
输出:
The journey of a thousand miles begins with one step.
这就是在 C++ 中创建多行字符串文字的全部内容。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论