我正在努力让我的专栏对齐我在学校的任务。方向是确保每个列标题与其各自的列正确对齐。我已经尝试了迄今为止在网上找到的所有内容,包括cout.width()和setw(),这两者都不起作用。我希望这不是由于我错误地实施了这些方法,尽管我想不出任何其他原因为什么他们不工作。该作业特别具有2个学生姓名作为示例。琼斯,鲍勃和华盛顿,乔治。由于一个学生和下一个学生的字符数量差别很大,所以这些列不会对齐。我知道设置一个列宽应该可以解决这个问题,但在我看来并不是这样。然后,我提供的代码是使用setw()方法,但我可以提供如何尝试使用cout.width()(如果需要)。任何帮助是极大的赞赏。使用C++进行列对齐
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
using std::cout;
using std::cin;
using namespace std;
const int ARRAYSIZE = 2;
struct studentData{
string lastName;
string firstName;
float studentGpa;
}studentArray[ARRAYSIZE];
void displayData(int a);
int main()
{
int counter = 0;
for (int a = 0; a < ARRAYSIZE; a++)
{
cout << "Enter last name: " << endl;
cin >> studentArray[a].lastName;
cout << "Enter first name: " << endl;
cin >> studentArray[a].firstName;
cout << "Enter GPA: "<< endl;
cin >> studentArray[a].studentGpa;
counter++;
}
cout << "\n\n";
displayData(counter);
return 0;
}
void displayData(int a)
{
int newSize = a;
cout << left << setw(20) <<"\nName(Last, First)";
cout << right << setw(20) << "GPA\n";
for (int z = 0; z < newSize; z++)
{
cout << studentArray[z].lastName << ", " << studentArray[z].firstName;
cout << right << setw(20) << fixed << setprecision(2) <<studentArray[z].studentGpa << endl;
}
}
我的控制台输入/输出:
Enter last name:
Jones
Enter first name:
Bob
Enter GPA:
3.0
Enter last name:
Washington
Enter first name:
George
Enter GPA:
4.0
Name(Last, First) GPA
Jones, Bob 3.00
Washington, George 4.00
你真了不起。非常感谢。感谢底部的链接,非常了解。 – JoeX