简体   繁体   English

我怎样才能缩进cout输出?

[英]How can I indent cout output?

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. 如何缩进输出以使用' - '字符缩进每个值。

您可以构造一个字符串以包含一些字符的重复:

std::cout << std::string(level, '-') << root->value << std::endl;

cout has special characters, below are two: cout有特殊字符,下面是两个:

'\t' - tab
'\n' - new line

Hope it helped. 希望它有所帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM