【问题标题】:Smart way to format tables on stdout in C在 C 中格式化标准输出上的表格的智能方法
【发布时间】:2011-12-18 00:09:35
【问题描述】:

我正在尝试使用数字数据将表格写入标准输出。我想格式化以便数字对齐:

1234     23
 312   2314
  12    123

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

【问题讨论】:

  • 查看<iomanip>中的std::setwstd::setfill
  • 有没有办法不用?我知道这听起来很奇怪,但我想让我的代码尽可能可移植
  • @Blackie123 : iomanip 是 C++ 标准库附带的头文件——你找不到任何 more 可移植的...
  • 好吧,你说服了我 :) 谢谢

标签: c format stdout tabular


【解决方案1】:

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]);
}

打印:

    22     22
 52352  52352
   532    532

类似的事情可以通过复杂而冗长的 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";
}

【讨论】:

  • 我不太关心“纯 C++”,但类型安全确实不错... ;-]
  • 熟悉%d的人比熟悉%i的人多。
  • 我添加了 iostreams/iomanip 版本以获得良好的效果。其实还不错。
  • @ildjarn: 或者只是做一个std::ostream format_cout(std::cout.rdbuf()); 并在单独的流上设置标志以避免混乱
  • 或使用ostringstream进行格式化,然后将字符串传递给cout
【解决方案2】:

对于c,使用“%6d”指定打印,即

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

对于 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;
}

别忘了#include &lt;iomanip&gt;

出于类型安全的原因,强烈建议使用 cout 而不是 printf。 如果我没记错的话,Boost 有一个 printf 的类型安全替代品,所以你可以使用 而不是你需要格式字符串,参数形式。

【讨论】:

  • 每个操作之前不需要调用setw吗?
【解决方案3】:

为了好玩:

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

输出:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2013-11-12
    • 2021-08-17
    • 1970-01-01
    相关资源
    最近更新 更多