2013-11-22 22 views
0

解決!襯砌立柱

enter image description here

這是我寫的:

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; 
} 

但如果第一個名字是幾個大字分揀機或大於第二個名字大,他們變得錯位。我將如何保持每列均勻對齊?

+0

做了'運輸及工務局局長(20)'輸出名稱 –

+0

似乎並沒有工作之前,它把下學生姓名「工時」 –

+0

@Bob其實,我設法操縱我的代碼,現在它調整得很好,謝謝。 –

回答

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; 
    } 
} 
+0

我實際上已經解決了我的問題。但是,謝謝你花時間回答。 +1 –