C++ 输出对齐的列

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

Output aligned columns

c++cout

提问by mikey

I am learning C++. I have a problem formatting the output of my program. I would like to print there columns perfectly aligned but so far I cannot do it, here is my code:

我正在学习 C++。我在格式化程序输出时遇到问题。我想在那里打印完全对齐的列,但到目前为止我无法做到,这是我的代码:

int main()
{
    employee employees[5];

    employees[0].setEmployee("Stone", 35.75, 053);
    employees[1].setEmployee("Rubble", 12, 163);
    employees[2].setEmployee("Flintstone", 15.75, 97);
    employees[3].setEmployee("Pebble", 10.25, 104);
    employees[4].setEmployee("Rockwall", 22.75, 15);

    printEmployees(employees, 5);

    return 0;
}

// print the employees in my array
void printEmployees(employee employees[], int number)
{
    int i;

    for (i=0; i<number; i++) {
        employees[i].printEmployee();// this is the method that give me problems
    }
    cout << "\n";
}

in the class employee I have the print employee method:

在班级员工中,我有打印员工方法:

void printEmployee() const
{
    cout << fixed;
    cout << surname << setw(10) << empNumber << "\t" << setw(4) << hourlyRate << "\n";
}

Problem is when I print "flinstones" line the emp number and rate are not lined up. something like this happens:

问题是当我打印“flinstones”行时,emp 号和费率没有对齐。发生这样的事情:

Stone        43 35.750000
Rubble       163    12.000000
Flintstone        97    15.750000
Pebble       104    10.250000
Rockwall        15  22.750000

Can anybody help me? (I tried to add tabs.. but it didn't help)

有谁能够帮助我?(我试图添加标签..但它没有帮助)

回答by AB Bolim

In the class employee of print employee method: Use this line to print.

在打印员工方法的类员工中:使用这一行打印。

cout << setw(20) << left << surname << setw(10) << left << empNumber << setw(4) << hourlyRate << endl;

You forgot to add "<< left". This is required if you want left aligned.

您忘记添加“ << left”了。如果你想左对齐,这是必需的。

Hope it ll useful.

希望它会有用。

回答by Jerry Coffin

You need to set a width beforeyou print out the name to get other things to line up after that. Something on this general order:

您需要打印名称之前设置宽度以便在此之后排列其他内容。关于这个一般顺序的东西:

cout << left << setw(15) << surname 
     << setw(10) << empNumber << "\t" 
     << setw(4) << hourlyRate << "\n";

I'd (at least normally) avoid trying to mix fixed-width fields with tabs as well. It's generally easier to just use widths to align things.

我(至少通常情况下)也避免尝试将固定宽度的字段与制表符混合使用。使用宽度来对齐通常更容易。