Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smart way to format tables on stdout in C

I am trying to write table to stdout with numerical data. I would like to format so that numbers are aligned like:

1234     23
 312   2314
  12    123

I know that max length of the number is 6 chars, is there a smart way to know how many spaces needs to be output before number so it looks exactly like this?

like image 551
Blackie123 Avatar asked Nov 25 '25 11:11

Blackie123


2 Answers

printf may be the quickest solution:

#include <cstdio>

int a[] = { 22, 52352, 532 };

for (unsigned int i = 0; i != 3; ++i)
{
    std::printf("%6i %6i\n", a[i], a[i]);
}

Prints:

    22     22
 52352  52352
   532    532

Something similar can be achieved with an arduous and verbose sequence of iostream commands; someone else will surely post such an answer should you prefer the "pure C++" taste of that.


Update: Actually, the iostreams version isn't that much more terrible. (As long as you don't want scientific float formatting or hex output, that is.) Here it goes:

#include <iostreams>
#include <iomanip>

for (unsigned int i = 0; i != 3; ++i)
{
    std::cout << std::setw(6) << a[i] << " " << std::setw(6) << a[i] << "\n";
}
like image 182
Kerrek SB Avatar answered Nov 28 '25 01:11

Kerrek SB


For c, use "%6d" to specify printing, i.e.

for (unsigned i = 0; i < ROWS(a); ++i) {
    for (unsigned j = 0; j < COLS(a); ++j) 
        printf("%6d ", a[i][j]);
    printf("\n");
}

For c++,

for (unsigned i = 0; i < ROWS(a); ++i) {
    for (unsigned j = 0; j < COLS(a); ++j) 
         std::cout  << a[i][j] << ' ';  
    std::cout << std::setw(6) << std::endl;
}

Don't forget to #include <iomanip>.

Use of cout is strongly recommended over printf for type safety reasons. If I remember correctly, Boost has a type-safe replacement for printf, so you can use that instead of you require the format-string, args form.

like image 38
moshbear Avatar answered Nov 28 '25 02:11

moshbear



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!