How can I indent cout output?
Asked Answered
P

3

16

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.

Photoreceptor answered 11/10, 2009 at 10:6 Comment(0)
E
32

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

std::cout << std::string(level, '-') << root->value << std::endl;
Emanuel answered 11/10, 2009 at 10:11 Comment(3)
@Aviraldg - read the question. The indent is to consist of '-' chars.Emanuel
Also, please don't use '\t'. On most consoles this will render as an 8-space tab, which is horrendously wide.Nussbaum
to do a wider indentation but not as wide as a tab, just multiply level with the width you want std::string(level*2, ' ')Spreader
C
2

cout has special characters, below are two:

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

Hope it helped.

Clasping answered 15/10, 2009 at 19:18 Comment(0)
S
1

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
Shrubbery answered 23/3, 2019 at 15:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.