Search code examples
cformatstdouttabular

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?


Solution

  • 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";
    }