如何使用cout设置固定宽度
How to set a fixed width with cout?
我想用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/
相关文章:
- 如何检查是否定义了固定宽度的整数
- 当我尝试将范围值存储为 8 位的固定宽度整数时,它向我显示一些其他值 [ASCII]
- 是否有缺少固定宽度类型(intXX_t)的平台
- 如何在调整列表视图大小时将标题宽度设置为等于其列表视图控件宽度
- 何时应使用 C++ 固定宽度整数类型,它们如何影响性能?
- 无法获得固定的设置精度双精度以显示小数位
- 使用固定宽度整数时,C 98 pedtical错误
- 为什么固定宽度类型会委托回基元
- 有没有理由不使用固定宽度类型
- 如何在 Windows 窗体应用程序 (C++) 中使用固定宽度整数
- 如何将文本的宽度设置回 0,以便我可以废话
- iomanip /固定宽度持久性
- 为什么 std::setprecision(6) 在固定宽度模式式传输超过 6 位数字
- 在 STL 中使用 void* 作为固定宽度记录
- 删除浮点数上的科学记数法,而不强制固定宽度
- 无论如何,我可以在直接写入文本布局中将宽度和布局宽度设置为相同
- 为什么 stoi、stol 不是固定宽度的整数
- 在标准C++中是否存在固定宽度的布尔类型
- Iostream中包含的Ctype方法默认情况下在程序中的固定区域设置中工作吗
- 如何使用cout设置固定宽度