格式化C ++输出两列不同的对齐方式

时间:2016-02-19 21:52:07

标签: c++ formatting output cout

这是我的代码:

cout << fixed <<showpoint<<setprecision(2);
cout << setw(10) << left << "Employee:"<< right << setw(9) << name <<endl;
cout << setw(10) << left << "Hours Worked:"<< right << setw(9) << hrWork <<endl; 
cout << setw(10) << left << "Hourly Rate:"<< right << setw(9) << hrRate <<endl;
cout << setw(10) << left  << "Total Wages:"<< right << setw(9) << tWages <<endl << endl;

cout << left << setw(10) << "Federal Withholding:"<< right << setw(9) << fedW <<endl;
cout << left << setw(10) << "State Withholding:"<< right << setw(9) << staW <<endl;
cout << left << setw(10) << "Hospitalization:"<< right << setw(9) << hosp <<endl;
cout << left << setw(10) << "Union Dues:"<< right << setw(9) << uniDues <<endl;
cout << left << setw(10) << "Total Deductions:"<< right << setw(9) << tDeduc <<endl;
cout << left << setw(10) << "Net Pay:"<< right << setw(9) << netP <<endl;

这是我当前的输出(我尝试过设置(w)和多种方式的辩护。这是我能得到的最接近的输出):

Employee:   Anthony
Hours Worked:    20.00
Hourly Rate:     8.75
Total Wages:   175.00

Federal Withholding:    31.50
State Withholding:     7.88
Hospitalization:    25.65
Union Dues:     3.50
Total Deductions:    68.53
Net Pay:     106.47

这就是我的目标(两列一对齐左侧,另一列右侧):

Employee:             Anthony
Hours Worked:           20.00
Hourly Rate:             8.75
Total Wages:           175.00

Federal Withholding:    31.50
State Withholding:       7.88
Hospitalization:        25.65
Union Dues:              3.50
Total Deductions:       68.53
Net Pay:               106.47

我该怎么做?谢谢

1 个答案:

答案 0 :(得分:1)

左侧大多数字符串长度超过10个字符,请使用e,g,setw(25)。

相关问题