在 C 中创建多行字符串文字

发布于 2025-03-06 14:35:47 字数 3337 浏览 4 评论 0

这篇文章将讨论如何在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

隐诗

暂无简介

文章
评论
28 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文