如果我正在制作一个数据表来显示几个函数的结果,我如何使用 setw((、left 和 right 关键字创建一个格式如下的表:
Height 8
Width 2
Total Area 16
Total Perimeter 20
请注意表格的整体"宽度"是恒定的(大约 20 个空格(。但是
左边的元素是左对齐的,右边的值是右对齐的。#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
struct Result
{
std::string Name;
int Value;
};
int main()
{
std::vector<Result> results = { {"Height", 8}, {"Width", 2}, {"Total Area", 16}, {"Total Perimeter", 20} };
for (auto result : results)
{
std::cout << std::setw(16) << std::left << result.Name;
std::cout << std::setw(4) << std::right << result.Value << std::endl;
}
return 0;
}
你可以做这样的事情:
// "Total Perimiter" is the longest string
// and has length 15, we use that with setw
cout << setw(15) << left << "Height" << setw(20) << right << "8" << 'n';
cout << setw(15) << left << "Width" << setw(20) << right << "2" << 'n';
cout << setw(15) << left << "Total Area" << setw(20) << right << "16" << 'n';
cout << setw(15) << left << "Total Perimeter" << setw(20) << right << "20" << 'n';