C++和表格格式打印

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3867122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:55:45  来源:igfitidea点击:

C++ and table format printing

c++

提问by Avinash

I am looking for how to print in C++ so that table column width is fixed. currently I have done using spaces and |and -, but as soon as number goes to double digit all the alignment goes bad.

我正在寻找如何在 C++ 中打印,以便固定表格列宽。目前我已经使用了空格和|-,但是一旦数字变为两位数,所有对齐都会变坏。

|---------|------------|-----------|
| NODE    |   ORDER    |   PARENT  |
|---------|------------|-----------|
|  0      |     0      |           |
|---------|------------|-----------|
|  1      |     7      |     7     |
|---------|------------|-----------|
|  2      |     1      |     0     |
|---------|------------|-----------|
|  3      |     5      |     5     |
|---------|------------|-----------|
|  4      |     3      |     6     |
|---------|------------|-----------|
|  5      |     4      |     4     |
|---------|------------|-----------|
|  6      |     2      |     2     |
|---------|------------|-----------|
|  7      |     6      |     4     |
|---------|------------|-----------|

回答by JoshD

You can use the std::setwmanipulator for cout.

您可以将std::setw操纵器用于 cout。

There's also a std::setfillto specify the filler, but it defaults to spaces.

还有一个std::setfill用于指定填充符,但它默认为空格。

If you want to center the values, you'll have to do a bit of calculations. I'd suggest right aligning the values because they are numbers (and it's easier).

如果要使值居中,则必须进行一些计算。我建议正确对齐这些值,因为它们是数字(而且更容易)。

cout << '|' << setw(10) << value << '|' setw(10) << value2 << '|' << endl;

Don't forget to include <iomanip>.

不要忘记包含<iomanip>.

It wouldn't be much trouble to wrap this into a general table formatter function, but I'll leave that as an exercise for the reader :)

把它包装成一个通用的表格格式化函数不会很麻烦,但我会把它留给读者作为练习:)

回答by Donotalo

You can use the beautiful printf(). I find it easier & nicer for formatting than cout.

您可以使用美丽的printf(). 我发现格式化比cout.

Examples:

例子:

int main()
{
    printf ("Right align: %7d:)\n", 5);
    printf ("Left align : %-7d:)\n", 5);

    return 0;
}