如何以本地和优雅的方式在C++中打印多行内容?

huangapple go评论136阅读模式
英文:

How do we print multi-line content in c++ in an native and elegant way?

问题

我正在尝试像练习一样打印这样的东西:

  *
 ***
*****
 ***
  *

我一直在使用C++将每一行打印为单独的语句。它可以通过测试。

然而,我在Python中学到了我们可以这样做:

s = """
  *
 ***
*****
 ***
  *
"""
print(s)

它可以干净地完成任务。所以我一直在想:在C++中有没有一个优雅的等价方法?

我使用的所有搜索都需要使用\nstd::endl作为换行符,但我不想这样做。

英文:

I am trying to print stuff like this like an exercise:

  *
 ***
*****
 ***
  *

and I have been using c++ to print every line in a separate statement. It can pass the tests all right.

However, I have learnt in python that we can do something like this:

s = """
  *
 ***
*****
 ***
  *
"""
print(s)

and it does the job neatly.
So I have been wondering: Is there an elegant equivalent in c++?
The searching I have used all need using \n or std::endl as line breaks, which I do not want to do.

答案1

得分: 0

只需使用多行字符串字面值,如下所示:

#include <iostream>

const char *s = "  *  \n"
               " *** \n"
               "*****\n"
               " *** \n"
               "  *  \n";

int main()
{
    std::cout << s;
    return 0;
}
英文:

Just use multiline string literals, like this :

#include &lt;iostream&gt;

const char *s= &quot;  *  \n&quot;
               &quot; *** \n&quot;
               &quot;*****\n&quot;
               &quot; *** \n&quot;
               &quot;  *  \n&quot;;

int main()
{
    std::cout &lt;&lt; s;
    return 0;
}

huangapple
  • 本文由 发表于 2023年6月29日 16:30:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76579322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定