0

解决了!

在此处输入图像描述

这是我写的:

cout << setw(4) << "Students";
cout << setw(20) << "Hours Worked";
cout << setw(20) << "of Total Hours";
cout << endl;

for (int i = 0; i < students; i++)
{
    cout << setw(20);
    cout << names[i];
    cout << setw(10) << hours[i];
    cout << setw(10) << percent[i];
    cout << endl;
}

但是,如果第一个名称比第二个名称多几个字符或大于第二个名称,它们就会错位。我将如何保持每列对齐?

4

1 回答 1

1

尝试这样的事情:

#include<iostream>
#include <iomanip>   
#include<string>

using namespace std;


int main()
{
  int students = 5;
  string names[5] = {"a","bccc","c","d","ecsdfsdfasdasasf"};
  int hours[5] = {1,2,3,4,5};
  int percent[5] = {10,20,30,40,54};

  string column("Students");

  int maxStringSize = 0;
  int sizeOfStudentColumn = column.length();

  for(int i = 0; i < 5; ++i)
  {
    if(maxStringSize < names[i].length())
     maxStringSize = names[i].length();
  }

  if(sizeOfStudentColumn > maxStringSize)
    maxStringSize = sizeOfStudentColumn;

  cout<<"max size: "<<maxStringSize<<endl;

  cout << setw(4) << "Students";
  cout << setw(maxStringSize + 5) << "Hours Worked";
  cout << setw(20) << "of Total Hours";
  cout << endl;

  for (int i = 0; i < students; i++)
  {
//    cout << setw(20);
    cout << names[i];
    int diff = maxStringSize - names[i].length();
    cout << setw(diff + 5 ) << hours[i];
    cout << setw(20) << percent[i];
    cout << endl;
  }
}
于 2013-11-22T05:07:15.043 回答