你能在字符串文字中放置中断吗?

Can you put breaks in a string literal?

本文关键字:中断 字符串 文字      更新时间:2023-10-16

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

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字符即可强制换行

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

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

const string PROGRAM_DESCRIPTION = "Program will calculate the amountn"
"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.";

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

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

输出:

this string
is for real

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

字符串中添加n,您希望换行的位置。

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

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

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

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

右?

答案很好,但是我的提议是将rn用于新行。在这里阅读更多内容,这两个符号应该始终有效(除非您使用的是 Atari 8 位操作系统)。

还有一些解释。

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

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