我尝试将我的输出格式化为:
1 [tab] First Name: John [tab] Last Name: Smith [tab] Age: 20 [tab]daysInCourse: {35, 40, 55} Degree Program: Security
我当前的代码是:
{
cout << left << setw(15) << studentID;
cout << left << setw(15) << "First Name: " << FN;
cout << left << setw(15) << "Last Name: " << LN;
cout << left << setw(15) << "Email " << studentEmail;
cout << left << setw(15) << "Age: " << age;
cout << left << setw(15) << "{" << days[0] << ", " << days[1] << ", " << days[2];
cout << left << setw(15) << "Degree Program: ";
}我处理了每一行的setw值,但似乎不能正确处理。setw函数是否只需要与特定值一起使用?
发布于 2020-03-04 19:46:31
注意:我担心您发布的数据包含真实的电子邮件地址和真人信息,这些信息可能是隐私的,也可能不是受保护的。如果是这样的话,我认为这是对隐私的侵犯,这是非法的。即使得到同意,也没有必要在这个论坛上发布私人数据;我建议您从您的帖子中删除这些数据,并且以后不要再这样做。
正如注释中提到的,setw操纵器仅应用于下一个字符串,因此
cout << left << setw(15) << "{" << days[0] << ", " << days[1] << ", " << days[2];将仅将字符{的宽度设置为15 (类似于行中的"First Name: "等)。还值得注意的是,如果字符串超过指定的宽度,那么它将推入下一个内容并破坏列的对齐方式;因此,您需要考虑最大可能的内容来设置宽度。
下面是一个实现所需内容的工作示例,它使用stringstream在打印字符串之前形成字符串(以便setw应用于整个内容):
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
// ------------------------------------------------------------------------
struct Student
{
std::string ID, First, Last, Email, Degree;
unsigned age;
std::vector<unsigned> days;
Student( std::string ID, std::string First, std::string Last, unsigned age,
std::string Email, std::string Degree, std::vector<unsigned> days )
: ID(ID), First(First), Last(Last), age(age), Email(Email), Degree(Degree), days(days)
{}
};
std::ostream& operator<< ( std::ostream& os, const Student& s ) {
std::ostringstream ss;
ss << "First Name: " << s.First;
os << std::left << std::setw(25) << ss.str();
ss.str("");
ss << "Last Name: " << s.Last;
os << std::left << std::setw(35) << ss.str();
ss.str("");
ss << "Email: " << s.Email;
os << std::left << std::setw(50) << ss.str();
ss.str("");
ss << "Age: " << s.age;
os << std::left << std::setw(10) << ss.str();
ss.str("");
ss << "{" << s.days.at(0) << ", " << s.days.at(1) << ", " << s.days.at(2) << "}";
os << std::left << std::setw(20) << ss.str();
ss.str("");
ss << "Degree Program: " << s.Degree;
os << std::left << std::setw(30) << ss.str();
ss.str("");
return os << std::endl;
}
// ------------------------------------------------------------------------
int main() {
std::cout << Student("A3","Robert","Smith",19,"example@foo.com","SOFTWARE",{20,40,33});
std::cout << Student("A4","Alice","Smith",22,"example@bar.net","SECURITY",{50,58,40});
}输出:
First Name: Robert Last Name: Smith Email: example@foo.com Age: 19 {20, 40, 33} Degree Program: SOFTWARE
First Name: Alice Last Name: Smith Email: example@bar.net Age: 22 {50, 58, 40} Degree Program: SECURITY 请注意,我为每个字段设置了不同的宽度,具体取决于内容的预期长度。例如,电子邮件地址可以很长,但期限很少会超过两位数。
https://stackoverflow.com/questions/60481700
复制相似问题