C++ 如何缩进 cout 输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1550329/
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
How can I indent cout output?
提问by Fantomas
I'm trying to print binary tree
我正在尝试打印二叉树
void print_tree(Node * root,int level )
{
if (root!=NULL)
{
cout<< root->value << endl;
}
//...
}
How can I indent output in order to indent each value with level '-' chars.
如何缩进输出以缩进带有级别“-”字符的每个值。
回答by Daniel Earwicker
You can construct a string to contain a number of repitions of a character:
您可以构造一个字符串来包含一个字符的多个重复:
std::cout << std::string(level, '-') << root->value << std::endl;
回答by vinnybad
cout has special characters, below are two:
cout 有特殊字符,下面是两个:
'\t' - tab
'\n' - new line
Hope it helped.
希望它有所帮助。
回答by leanid.chaika
You also can indent with columns, and think about first column size, then second column size and etc. You can find longest name in every column and then set width for all items in this column with padding and align you wish. You can do it dynamically first search items size, then select width, or you can do it statically like:
你也可以用列缩进,然后考虑第一列的大小,然后是第二列的大小等等。你可以在每一列中找到最长的名称,然后用你想要的填充和对齐来设置该列中所有项目的宽度。您可以先动态搜索项目大小,然后选择宽度,也可以静态进行,例如:
#include <iomanip>
#include <iostream>
#include <sstream>
void print_some()
{
using namespace std;
stringstream ss;
ss << left << setw(12) << "id: " << tank_name << '\n';
ss << left << setw(12) << "texture: " << texture_name << '\n';
ss << left << setw(12) << "uv_rect: ";
// clang-format off
ss << left <<setprecision(3) << fixed
<< setw(7) << r.pos.x << ' '
<< setw(7) << r.pos.y << ' '
<< setw(7) << r.size.x << ' '
<< setw(7) << r.size.y << '\n';
// clang-format on
ss << left << setw(12) << "world_pos: " << pos.x << ' ' << pos.y << '\n';
ss << left << setw(12) << "size: " << size.x << ' ' << size.y << '\n';
ss << left << setw(12) << "angle: " << angle << '\n';
}
The output may look like:
输出可能如下所示:
id: tank_spr
texture: tank.png
uv_rect: 0.300 0.500 0.500 0.500
world_pos: 0.123 0.123
size: 1.000 0.300
angle: 270.000