完成一个长项目,最后一步是确保我的数据排在正确的列中。容易的只是我在这方面遇到了麻烦,而且我做这件事的时间比我想承认的要长,我看了很多视频,真的不知道该怎么办。所以这里有一小段我遇到麻烦的代码:
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
cout << "Student Grade Summaryn";
cout << "---------------------nn";
cout << "BIOLOGY CLASSnn";
cout << "Student Final Final Lettern";
cout << "Name Exam Avg Graden";
cout << "----------------------------------------------------------------n";
cout << "bill"<< " " << "joeyyyyyyy" << right << setw(23)
<< "89" << " " << "21.00" << " "
<< "43" << "n";
cout << "Bob James" << right << setw(23)
<< "89" << " " << "21.00" << " "
<< "43" << "n";
}
这适用于第一个条目,但bob-james条目的数字都歪斜了。我以为赛斯应该允许你忽略这一点?我错过了什么?感谢
它并不像你想象的那样工作。std::setw
仅为下一次插入设置字段的宽度(即,它不是"粘性")。
试试这样的东西:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << "Student Grade Summaryn";
cout << "---------------------nn";
cout << "BIOLOGY CLASSnn";
cout << left << setw(42) << "Student" // left is a sticky manipulator
<< setw(8) << "Final" << setw(6) << "Final"
<< "Letter" << "n";
cout << setw(42) << "Name"
<< setw(8) << "Exam" << setw(6) << "Avg"
<< "Grade" << "n";
cout << setw(62) << setfill('-') << "";
cout << setfill(' ') << "n";
cout << setw(42) << "bill joeyyyyyyy"
<< setw(8) << "89" << setw(6) << "21.00"
<< "43" << "n";
cout << setw(42) << "Bob James"
<< setw(8) << "89" << setw(6) << "21.00"
<< "43" << "n";
}
还相关:What';setw()怎么了?
操纵器<< right << setw(23)
正在告诉ostream
您想要字符串"89"设置在23个字符宽的字段的右侧边缘。没有什么可以告诉ostream您希望该字段从哪里开始,但是,除了由于最后一行换行符。并且<< "bill"<< " " << "joeyyyyyyy"
向输出写入更多的字符与<< "Bob James"
相比,第二行的23个字符宽的字段在第一行的同一个字段的左边开始。
流操纵器会影响流式处理的下一个输入/输出值,然后一些操纵器(包括setw()
)会重置。因此,您需要在输出文本字符串之前设置宽度和对齐方式,而不是之后。
试试类似的东西:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void outputStudent(const string &firstName, const string &lastName,
int finalExam, float finalAvg, int letterGrade)
{
cout << setw(40) << left << (firstName + " " + lastName) << " "
<< setw(6) << right << finalExam << " "
<< setw(6) << right << fixed << setprecision(2) << finalAvg << " "
<< setw(7) << right << letterGrade << "n";
}
int main()
{
cout << "Student Grade Summaryn";
cout << "---------------------nn";
cout << "BIOLOGY CLASSnn";
cout << "Student Final Final Lettern";
cout << "Name Exam Avg Graden";
cout << "--------------------------------------------------------------n";
outputStudent("bill", "joeyyyyyyy", 89, 21.00, 43);
outputStudent("Bob", "James", 89, 21.00, 43);
cin.get();
return 0;
}
输出:
Student Grade Summary
---------------------
BIOLOGY CLASS
Student Final Final Letter
Name Exam Avg Grade
--------------------------------------------------------------
bill joeyyyyyyy 89 21.00 43
Bob James 89 21.00 43