格式化表格中的输出,C ++

时间:2011-07-19 23:16:59

标签: c++ console format tabular

如何在C ++表格中将数据输出到控制台?在C#中有一个问题,但我需要用C ++。

这个,除了C ++:How To: Best way to draw table in console app (C#)

4 个答案:

答案 0 :(得分:10)

以下是iomanip所拥有的一小部分样本:

#include <iostream>
#include <iomanip>

int main(int argc, char** argv) {
    std::cout << std::setw(20) << std::right << "Hi there!" << std::endl;
    std::cout << std::setw(20) << std::right << "shorter" << std::endl;
    return 0;
}

您还可以执行其他操作,例如设置浮点数的精度,更改使用setw时用作填充的字符,输出基数10以外的数字等等。

http://cplusplus.com/reference/iostream/manipulators/

答案 1 :(得分:5)

你不能做一些非常类似于C#例子的事情:

String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", arg0, arg1, arg2, arg3);

像:

printf("|%5s|%5s|%5s|%5s|", arg0, arg1, arg2, arg3);

以下是我用来做这个的参考:http://www.cplusplus.com/reference/clibrary/cstdio/printf/

答案 2 :(得分:3)

我无法找到我喜欢的东西,所以我做了一个。在https://github.com/haarcuba/text-table

找到它

这是其输出的例子:

+------+------+----+
|      |Sex   | Age|
+------+------+----+
|Moses |male  |4556|
+------+------+----+
|Jesus |male  |2016|
+------+------+----+
|Debora|female|3001|
+------+------+----+
|Bob   |male  |  25|
+------+------+----+

答案 3 :(得分:0)

检查列值长度,并记住格式值的长度。

printf(" %-4s| %-10s| %-5s|\n", "ID", "NAME", "AGE");

看看MySQL shell界面是如何设计的,它会给你一个好主意。

相关问题