如何用cout设置固定宽度?

And*_*Kim 11 c++ cout

我想使用 C++ 计算出类似输出的表格。它应该看起来像这样

Passes in Stock : Student Adult
-------------------------------
Spadina               100   200
Bathurst              200   300
Keele                 100   100
Bay                   200   200
Run Code Online (Sandbox Code Playgroud)

但我的总是看起来像

Passes in Stock : Student Adult
-------------------------------
Spadina               100   200
Bathurst               200   300
Keele               100   100
Bay               200   200
Run Code Online (Sandbox Code Playgroud)

我的输出代码

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;

    }
Run Code Online (Sandbox Code Playgroud)

我该如何更改它,使其看起来像顶部的输出?

小智 7

使用 setw()

// setw example
#include <iostream>     // std::cout, std::endl
#include <iomanip>      // std::setw

int main () {
  std::cout << std::setw(10);
  std::cout << 77 << std::endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

https://www.cplusplus.com/reference/iomanip/setw/


小智 6

为了保持间距一致,您可以将标题的长度存储在数组中。

size_t headerWidths[3] = {
    std::string("Passes in Stock").size(),
    std::string("Student").size(),
    std::string("Adult").size()
};
Run Code Online (Sandbox Code Playgroud)

中间的东西,例如" : "学生和成人之间的空间,应被视为无关的输出,您无需将其纳入计算中。

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;
 }
Run Code Online (Sandbox Code Playgroud)