【问题标题】:Trouble formatting fstream output with unknown strength and int length使用未知强度和 int 长度格式化 fstream 输出时出现问题
【发布时间】:2019-04-01 23:08:25
【问题描述】:

我正在完成我正在处理的这个 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:

如果有人能帮助我做什么,我将不胜感激。非常感谢您的宝贵时间!

【问题讨论】:

    标签: c++ fstream


    【解决方案1】:

    第一个(最明显的)问题是您没有为球场名称设置字段宽度。默认情况下,它设置为 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 2014-08-23
      • 2017-06-27
      • 2021-10-29
      • 1970-01-01
      相关资源
      最近更新 更多