C++ 如何在字符串中放置断行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4529639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:39:30  来源:igfitidea点击:

How to put a break line in string?

c++stringwinapivisual-c++

提问by Ramilol

How can i put break line in string.
Something like this.

我怎样才能在字符串中放置断行。
像这样的东西。

string var = "hey
s";

Would be something like this.

会是这样的。

hey
s

回答by dshipper

You should just put a \nbetween heyand s. So:

你应该\nhey和之间放一个s。所以:

string var = "hey\ns";

回答by darioo

Line breaking can be achieved using Dan's advice:

可以使用 Dan 的建议实现换行:

string var = "hey\ns";

Note that you cannot do this the way you wanted:

请注意,您不能按照自己的方式执行此操作:

string var = "hey     // this is not
s";                   // valid code

and it's a design choice of C++.

它是 C++ 的设计选择。

Older languages generally do not allow you to define multiline strings.

较旧的语言通常不允许您定义多行字符串。

But, for example, Python does allow you exactly this:

但是,例如,Python 确实允许您这样做:

someString = """
    this is a
    multiline
    string
"""

and printing someStringwill give you a true multiline string.

和打印someString会给你一个真正的多行字符串。

You can forget about this when using C++, though.

不过,在使用 C++ 时,您可以忘记这一点。

回答by Lightness Races in Orbit

A line break is encoded as the char '\n'. So just write \ninto your string.

换行符被编码为 char '\n'。所以只需写入\n您的字符串。

回答by T???? W??????

You can also do this:

你也可以这样做:

string var =
"\
some text\n\
some more text\n\
and even more text\
";

and var would be equels to

和 var 将等于

some text
some more text
and even more text

回答by Nitin Jindal

you should try this string var = "hey"."/n"."s";

你应该试试这个字符串 var = "hey"."/n"."s";