开发者

How can I indent cout output?

开发者 https://www.devze.com 2022-12-08 19:23 出处:网络
I\'mtrying to print bin开发者_开发技巧ary tree void print_tree(Node * root,int level ) { if (root!=NULL)

I'm trying to print bin开发者_开发技巧ary 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.


You can construct a string to contain a number of repitions of a character:

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


cout has special characters, below are two:

'\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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号