在C中使用stdout格式化表的智能方法

Bla*_*123 2 c format stdout tabular

我试图用数值数据写表到stdout.我想格式化,以便数字对齐如下:

1234     23
 312   2314
  12    123
Run Code Online (Sandbox Code Playgroud)

我知道这个数字的最大长度是6个字符,是否有一种聪明的方法可以知道在数字之前需要输出多少空格,所以它看起来完全像这样?

Ker*_* SB 10

printf 可能是最快的解决方案:

#include <cstdio>

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

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

打印:

    22     22
 52352  52352
   532    532
Run Code Online (Sandbox Code Playgroud)

使用繁琐冗长的iostream命令序列可以实现类似的功能; 如果您更喜欢"纯C++"的味道,别人肯定会发布这样的答案.


更新:实际上,iostreams版本并没有那么糟糕.(只要你不想要科学的浮动格式或十六进制输出,就是这样.)这里有:

#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";
}
Run Code Online (Sandbox Code Playgroud)

  • 我添加了iostreams/iomanip版本以获得良好的衡量标准.实际上并不是太糟糕. (2认同)
  • @ildjarn:或者只是做一个`std :: ostream format_cout(std :: cout.rdbuf());`并在单独的流上设置标志以避免混乱 (2认同)