如何使用cout设置固定宽度

How to set a fixed width with cout?

本文关键字:固定宽度 设置 cout 何使用      更新时间:2023-10-16

我想用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;
    }

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

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

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;
 }

使用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;
}

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