英文:
How do we print multi-line content in c++ in an native and elegant way?
问题
我正在尝试像练习一样打印这样的东西:
*
***
*****
***
*
我一直在使用C++将每一行打印为单独的语句。它可以通过测试。
然而,我在Python中学到了我们可以这样做:
s = """
*
***
*****
***
*
"""
print(s)
它可以干净地完成任务。所以我一直在想:在C++中有没有一个优雅的等价方法?
我使用的所有搜索都需要使用\n
或std::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 <iostream>
const char *s= " * \n"
" *** \n"
"*****\n"
" *** \n"
" * \n";
int main()
{
std::cout << s;
return 0;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论