【问题标题】:Can you put breaks in a string literal?您可以在字符串文字中添加中断吗?
【发布时间】:2023-03-28 23:07:01
【问题描述】:

这是我正在使用的常量,它是这样拆分的,因为我不想滚动我的编辑器

const string PROGRAM_DESCRIPTION = "Program will calculate the amount "
"accumulated every month you save, until you reach your goal.";

int main() 
{
    cout << PROGRAM_DESCRIPTION;
    return 0;
}

当前在命令提示符中打印为

Program will calculate the amount accumulated every month you save,until you re
ach your goal.

当它打印出来时,我希望它打印在两个单独的行上,如下所示...

Program will calculate the amount accumulated every month you save,
until you reach your goal.

我不知道将 break 语句放在字符串中的什么位置,以便正确打印出来。

【问题讨论】:

  • 您是否尝试过使用\n 插入换行符?

标签: c++ newline


【解决方案1】:

只需插入一个\n 字符即可强制换行

const string PROGRAM_DESCRIPTION = "Program will calculate the amount "
"accumulated every month you save, \nuntil you reach your goal.";

【讨论】:

  • 谢谢你的作品。我曾尝试添加 /n,但我的“n”后面有一个空格,然后它出现在字符串中
  • 嗯,有些东西不见了。线索,想象它是 Windows 操作系统并创建了表单应用程序,而不是控制台。
【解决方案2】:

您可以在文字第一部分的末尾使用\n,如下所示:

const string PROGRAM_DESCRIPTION = "Program will calculate the amount\n"
"accumulated every month you save, until you reach your goal."; //   ^^

如果您不希望将文字分成几部分以提高可读性,则不必这样做:

const string PROGRAM_DESCRIPTION = "Program will calculate the amount accumulated every month you save,\nuntil you reach your goal.";

【讨论】:

    【解决方案3】:

    在 C++11 中,您可以使用原始字符串文字

    const char* stuff =
    R"foo(this string
    is for real)foo";
    std::cout << stuff;
    

    输出:

    this string
    is for real
    

    (出于迂腐的原因,我把这个答案放在这里,使用\n)

    【讨论】:

      【解决方案4】:

      在要换行的字符串中添加\n

      【讨论】:

        【解决方案5】:

        只需在 const 字符串中所需的位置插入换行符“\n”,就像在普通文字字符串中一样:

        const string PROGRAM_DESCRIPTION = "Program will calculate the amount\naccumulated every month you save, until you reach your goal.";
        
        cout << PROGRAM_DESCRIPTION;
        

        简单。就像我习惯使用文字字符串一样:

        cout << "Program will calculate the amount\naccumulated every month you save, until you reach your goal.";
        

        对吗?

        【讨论】:

          【解决方案6】:

          答案很好,但是我的提议是使用\r\n 换行。多阅读here,这两个符号应该始终有效(除非您使用的是 Atari 8 位操作系统)。

          还有一些解释。

          • \n - 换行。这应该将打印指针向下移动一行,但它可能会将打印指针设置为也可能不会将打印指针设置为开始 o 行。
          • \r - 回车。这会将行指针设置在行的开头,并且可能会或可能不会更改行。

          • \r\n - CR LF。将打印指针移动到下一行并将其设置在行首。

          【讨论】:

            猜你喜欢
            • 2021-05-17
            • 1970-01-01
            • 1970-01-01
            • 2018-07-05
            • 1970-01-01
            • 1970-01-01
            • 2010-10-12
            • 2013-09-04
            • 2012-02-21
            相关资源
            最近更新 更多