Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ and table format printing

Tags:

c++

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

|---------|------------|-----------|
| 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     |
|---------|------------|-----------|
like image 717
Avinash Avatar asked Oct 05 '10 19:10

Avinash


People also ask

What is print C?

Print function is used to display content on the screen. Approach: Some characters are stored in integer value inside printf function. Printing the value as well as the count of the characters.

What is formatted output using printf () statement explain it in C?

One, the printf (short for "print formatted") function, writes output to the computer monitor. The other, fprintf, writes output to a computer file. They work in almost exactly the same way, so learning how printf works will give you (almost) all the information you need to use fprintf.


2 Answers

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

There's also a std::setfill to specify the filler, but it defaults to spaces.

If you want to center the values, you'll have to do a bit of calculations. I'd suggest right aligning the values because they are numbers (and it's easier).

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

Don't forget to include <iomanip>.

It wouldn't be much trouble to wrap this into a general table formatter function, but I'll leave that as an exercise for the reader :)

like image 145
JoshD Avatar answered Sep 26 '22 19:09

JoshD


You can use the beautiful printf(). I find it easier & nicer for formatting than cout.

Examples:

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

    return 0;
}
like image 29
Donotalo Avatar answered Sep 26 '22 19:09

Donotalo