如何使用cout设置固定宽度? 我想用C++来输出一个类似表的输出。应该是这样的 Passes in Stock : Student Adult ------------------------------- Spadina 100 200 Bathurst 200 300 Keele 100 100 Bay 200 200

如何使用cout设置固定宽度? 我想用C++来输出一个类似表的输出。应该是这样的 Passes in Stock : Student Adult ------------------------------- Spadina 100 200 Bathurst 200 300 Keele 100 100 Bay 200 200,c++,cout,C++,Cout,然而我的总是看起来像 Passes in Stock : Student Adult ------------------------------- Spadina 100 200 Bathurst 200 300 Keele 100 100 Bay 200 200 我的输出代码 std::cout << "Passes in Stock : Studen

然而我的总是看起来像

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;

    }

std::cout为了保持一致的间距,可以将标题的长度存储在一个数组中

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;
 }
for(int i=0;i如果不在第一列设置固定with,那么在第二列和第三列设置固定with将没有多大用处。