Smart way to format tables on stdout in C

2020-07-24 16:19发布

问题:

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?

回答1:

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


回答2:

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.



回答3:

For fun:

#include <boost/spirit/include/karma.hpp>

namespace karma = boost::spirit::karma;

int main(int argc, const char *argv[])
{
    std::vector<std::vector<int>> a = 
        { { 1,2,3 },
          { 4,5,6 },
          { 7,8,9 },
          { 10,11,12 },
          { 13,14,15 }, };

    std::cout << karma::format(
             *karma::right_align(7, ' ') [ karma::int_ ] % '\n', a) << "\n";

    return 0;
}

output:

  1      2      3
  4      5      6
  7      8      9
 10     11     12
 13     14     15