Printing in C ++ and table format

I am looking for how to print in C ++ so that the width of the table column is fixed. I have currently used spaces and | and - , but as soon as the number goes to a double digit, all alignment worsens.

 |---------|------------|-----------| | NODE | ORDER | PARENT | |---------|------------|-----------| | 0 | 0 | | |---------|------------|-----------| | 1 | 7 | 7 | |---------|------------|-----------| | 2 | 1 | 0 | |---------|------------|-----------| | 3 | 5 | 5 | |---------|------------|-----------| | 4 | 3 | 6 | |---------|------------|-----------| | 5 | 4 | 4 | |---------|------------|-----------| | 6 | 2 | 2 | |---------|------------|-----------| | 7 | 6 | 4 | |---------|------------|-----------| 
+4
source share
2 answers

You can use the std::setw manipulator for cout.

Here is also std::setfill to indicate the filler, but by default it has spaces.

If you want to center the values, you have to calculate a little. I would suggest proper alignment of values, because they are numbers (and this is simpler).

 cout << '|' << setw(10) << value << '|' setw(10) << value2 << '|' << endl; 

Remember to include <iomanip> .

It would not be easy to wrap this in a common table formatting function, but I will leave this as an exercise for the reader :)

+8
source

You can use beautiful printf() . It's easier and easier for me to format than cout .

Examples:

 int main() { printf ("Right align: %7d:)\n", 5); printf ("Left align : %-7d:)\n", 5); return 0; } 
+5
source

All Articles