tags:

views:

42

answers:

2

Hi,

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     |
|---------|------------|-----------|
+4  A: 

You can use the setw funciton for cout. Check out http://www.cplusplus.com/reference/iostream/manipulators/setw/

There's also a 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 :)

JoshD
what is wrong then with following code
Avinash
what is wrong with following code `os << '|' << std::setfill('-') << std::setw(10) << '|' << std::setfill('-') << std::setw(10)<< '|' << std::setfill('-') << std::setw(10)<< '|' << std::endl; os << '|' << std::setfill(' ') << std::setw(10) << "NODE"<< '|' << std::setfill(' ') << std::setw(10) << "ORDER"<< '|' << std::setfill(' ') << std::setw(10) << "PARENT" << std::endl; os << '|' << std::setfill('-') << std::setw(10) << '|' << std::setfill('-') << std::setw(10) << '|' << std::setfill('-') << std::setw(10) << '|' << std::endl;`
Avinash
@Avinash: "What's wrong with this" isn't really a good question. Are you getting a compilation error? Is it formatted wrong? Please provide more. You can update your question with this...
JoshD
+2  A: 

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;
}
Donotalo
Avinash's comment to the accepted solution nicely highlights precisely why printf() is far superior to cout for formatted output. ;)
dandan78
yep. :)) thanks for the comment. otherwise i wouldn't see that!
Donotalo