我正在努力讓我的專欄對齊我在學校的任務。方向是確保每個列標題與其各自的列正確對齊。我已經嘗試了迄今爲止在網上找到的所有內容,包括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