在 C++ 中声明多行字符串

Jinku Hu 2023年1月30日 2021年1月4日
  1. 使用 std::string 类在 C++ 中声明多行字符串
  2. 使用 const char *符号来声明多行字符串文字
  3. 使用 const char *符号与反斜杠字声明多行字符串文字
在 C++ 中声明多行字符串

本文将介绍几种在 C++ 中如何声明多行字符串的方法。

使用 std::string 类在 C++ 中声明多行字符串

std::string 对象可以用一个字符串值初始化。在这种情况下,我们将 s1 字符串变量声明为 main 函数的一个局部变量。C++ 允许在一条语句中自动连接多个双引号的字符串字元。因此,在初始化 string 变量时,可以包含任意行数,并保持代码的可读性更一致。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

using std::cout; using std::vector;
using std::endl; using std::string;
using std::copy;

int main(){
    string s1 = "This string will be printed as the"
                " one. You can include as many lines"
                "as you wish. They will be concatenated";

    copy(s1.begin(), s1.end(),
         std::ostream_iterator<char>(cout, ""));
    cout << endl;

    return EXIT_SUCCESS;
}

输出:

This string will be printed as the one. You can include as many linesas you wish. They will be concatenated

使用 const char *符号来声明多行字符串文字

但在大多数情况下,用 const 修饰符声明一个只读的字符串文字可能更实用。当相对较长的文本要输出到控制台,而且这些文本大多是静态的,很少或没有随时间变化,这是最实用的。需要注意的是,const 限定符的字符串在作为 copy 算法参数传递之前需要转换为 std::string 对象。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::copy;

int main(){
    const char *s2 =
            "This string will be printed as the"
            " one. You can include as many lines"
            "as you wish. They will be concatenated";

    string s1(s2);

    copy(s1.begin(), s1.end(),
         std::ostream_iterator<char>(cout, ""));
    cout << endl;

    return EXIT_SUCCESS;
}

输出:

This string will be printed as the one. You can include as many linesas you wish. They will be concatenated

使用 const char *符号与反斜杠字声明多行字符串文字

另外,也可以利用反斜杠字符/来构造一个多行字符串文字,并将其分配给 const 限定的 char 指针。简而言之,反斜杠字符需要包含在每个换行符的末尾,这意味着字符串在下一行继续。

不过要注意,间距的处理变得更容易出错,因为任何不可见的字符,如制表符或空格,可能会将被包含在输出中。另一方面,人们可以利用这个功能更容易地在控制台显示一些模式。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::copy;

int main(){
    const char *s3 = "          This string will\n\
        printed as the pyramid\n\
    as one single string literal form\n";

    cout << s1 << endl;

    printf("%s\n", s3);

    return EXIT_SUCCESS;
}

输出:

          This string will
        printed as the pyramid
    as one single string literal form
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相关文章 - C++ String