在C中的stdout上格式化表格的智能方法 [英] Smart way to format tables on stdout in C

查看:111
本文介绍了在C中的stdout上格式化表格的智能方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用数字数据将表写入stdout.我想格式化,以便数字对齐:

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

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

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?

推荐答案

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

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

打印:

    22     22
 52352  52352
   532    532

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

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.

更新:实际上,iostreams版本并不可怕. (就是这样,只要您不希望科学的float格式或十六进制输出.)它就这样:

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

这篇关于在C中的stdout上格式化表格的智能方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆