我想用c ++来输出像输出这样的表。看起来应该是这样的
Passes in Stock : Student Adult
-------------------------------
Spadina 100 200
Bathurst 200 300
Keele 100 100
Bay 200 200
然而我总是看起来像
Passes in Stock : Student Adult
-------------------------------
Spadina 100 200
Bathurst 200 300
Keele 100 100
Bay 200 200
我的输出代码
std::cout << "Passes in Stock : Student Adult" << std::endl;
std::cout << "-------------------------------";
for (int i = 0; i < numStations; i++) {
std::cout << std::left << station[i].name;
std::cout << std::right << std::setw(18) << station[i].student << std::setw(6) << station[i].adult << std::endl;
}
如何更改它,使其看起来像顶部的输出?
答案 0 :(得分:1)
对于一致的间距,您可以将标题的长度存储在数组中。
size_t headerWidths[3] = {
std::string("Passes in Stock").size(),
std::string("Student").size(),
std::string("Adult").size()
};
中间的内容,例如" : "
学生和成人之间的空格应该被视为无关的输出,而不是计算中的因素。
for (int i = 0; i < numStations; i++) {
std::cout << std::left << std::setw(headerWidths[0]) << station[i].name;
// Spacing between first and second header.
std::cout << " ";
std::cout << std::right << std::setw(headerWidths[1]) << station[i].student
// Add space between Student and Adult.
<< " " << std::setw(headerWidths[2]) << station[i].adult << std::endl;
}