C++ 表对齐 - cout 和 iomanip

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27679569/
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 20:50:43  来源:igfitidea点击:

C++ table alignment - cout and iomanip

c++alignmentcout

提问by Babbzzz

I have a small alignment issue in my program.

我的程序中有一个小的对齐问题。

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    cout << setw(5) << "Sl. No:" << setw(15) << "Month" << setw(15) << "Name" << endl << endl;
    cout << setw(5) << 1 << setw(15) << "January" << setw(15) << "Abhilash" << endl;
    cout << setw(5) << 2 << setw(15) << "Februaury" << setw(15) << "Anandan" << endl;
    cout << setw(5) << 3 << setw(15) << "March" << setw(15) << "Abhilash" << endl;
    cout << setw(5) << 4 << setw(15) << "April" << setw(15) << "Anandan" << endl;

    return 0;
}

In the output I get, the names of the months are not right justified.

在我得到的输出中,月份的名称不合理。

Sl. No:          Month           Name

    1        January       Abhilash
    2      Februaury        Anandan
    3          March       Abhilash
    4          April        Anandan

What seems to be the problem?

似乎是什么问题?

回答by jxh

The string Sl. No:is 7 wide and you are trying to fit it into a 5 wide column. That pushes the first row over by 2 columns. Try making your first column 7 wide rather than 5 wide instead:

字符串Sl. No:为 7 宽,您正试图将其放入 5 宽的列中。这会将第一行推高 2 列。尝试将您的第一列设置为 7 宽而不是 5 宽:

cout << setw(7) << "Sl. No:" << setw(15) << "Month" << setw(15) << "Name"
     << endl << endl;
cout << setw(7) << 1 << setw(15) << "January" << setw(15) << "Abhilash"
     << endl;
//...

回答by user2649644

When you want to use setw, you have to count from the end of the output string, int, etc. So when you say

当你想使用setw时,你必须从输出字符串的末尾开始计数,int等。 所以当你说

 cout << setw(15) << "January";

It'll format 8 spaces in between since January is 7 characters. So in your example, you want to have

它将格式化 8 个空格,因为一月是 7 个字符。所以在你的例子中,你想要

 cout << setw(23) << "January";

That obviously depends if you keep your first output of '1' in the same place.

这显然取决于您是否将第一个输出 '1' 保留在同一位置。

回答by justWantToMakeATable

Oh you need to use spacing in front of the "month"

哦你需要在“月”前使用空格

    "  month"

not

不是

    "month"

the results will look like this

结果看起来像这样

     Month
    January

you may have to adjust the amount of spacing you use.

您可能需要调整您使用的间距量。