我正在完成这个c ++项目我正在努力获取用户输入,计算一些值,然后将所有数据写入文件。我的问题是我无法在文本文件中正确对齐值。我正在使用setw(),但是当用户输入的长度未知时,这并没有正确对齐所有内容。它只是与列混乱,使它们不对齐。
我尝试过使用固定操作符,左对齐,右对齐,没有太多运气
这是我写入文件的代码。
if (myfile.is_open()){
myfile << "BASKETBALL COURTS AREA REPORT\n\n";
myfile << "Court" << setw(25) << "Height" << setw(25) << "Width\n";
for(int i=0; i<n; i++){
myfile << names[i] << setw(25) << " " << arr1[i] << setw(25) << arr2[i] <<"\n\n";
}
}
myfile << "\nThe largest court is " << maxName << ": " << maximum << "\n" << "\n";
myfile << "Total area covered by all courts: " << totalArea;
I expect the columns to be completely aligned like in this picture:
However the actual output looks more like this:
如果有人可以帮我做什么,我会非常感激。非常感谢您的参与!
第一个(最明显的)问题是你没有为法院的名字设置字段宽度。默认情况下,它设置为0,因此每个名称都以显示整个名称所需的最小宽度打印。之后设置其他列宽度不会有太大作用。
要设置宽度,您可能需要浏览项目,找到最宽的项目,然后添加一些额外的空格以在列之间给出边距。
#include <iostream>
#include <sstream>
#include <iomanip>
#include <ios>
#include <string>
#include <algorithm>
#include <vector>
struct court {
std::string name;
int height;
int width;
};
int main() {
std::vector<court> courts {
{ "Auburn park", 12, 16},
{ "Alabama", 14, 17},
{"Wilsonville Stadium", 51, 123}
};
auto w = std::max_element(courts.begin(), courts.end(), [](court const &a, court const &b) { return a.name.length() < b.name.length(); })->name.length();
for (auto const &c : courts) {
std::cout << std::left << std::setw(w+5) << c.name
<< std::right << std::setw(5) << c.height
<< std::setw(5) << c.width << "\n";
}
}
结果:
Auburn park 12 16
Alabama 14 17
Wilsonville Stadium 51 123