【问题标题】:how to align different lengthed outputs C++如何对齐不同长度的输出C++
【发布时间】:2014-08-29 08:06:39
【问题描述】:

我已经尝试搜索很多关于此的帖子,但我仍然无法弄清楚这一点。假设我有一个循环,它从文本文件中读取行,然后将它们显示在屏幕上。我希望每个数据都对齐,但问题是数据可以是不同的长度,因此在 setw 中使用静态值是行不通的。 例如这里是一个文本文件

000000  apples      pears     2.00
000001  oranges     bannana   1.00

这是我希望它在屏幕上显示的样子,但我的屏幕看起来像这样

000000  apples      pears     2.00
000001 oranges    banana   1.00

它看到橙子比苹果长 1,然后将其向左移动超过 1。它对香蕉和梨做同样的事情

我如何像第一个例子一样对齐它(这是它在我的文本文件中的样子)

这是我正在使用的:

cout << account << setw(10) << fruit << setw(10) << fruit2 << setw(10) << money << endl;

我觉得 setw(10) 需要是非静态的。我也试过左右,也不行。

【问题讨论】:

  • 考虑使用boost.format
  • 我不能使用 boost,因为它不能有额外的库
  • 那就考虑使用printf

标签: c++ io alignment console-application


【解决方案1】:

如果你使用 std::string,我是这样解决这个问题的:

cout << left << setw(10) << account << setw(10) << fruit << setw(10 + strlen(fruit2.c_str()) -  strlen(fruit.c_str())) << fruit2 << endl;   

格式化时会考虑字符串的长度。您可以选择任意偏移量,只要水果名称不会太长(用“strawberries”代替“apples”会破坏格式

setw(10)

【讨论】:

    【解决方案2】:

    这几乎没有意义——如果你真的得到了那个结果,那听起来像是你的编译器有问题。我写了一个相当的演示,类似于你在问题中的内容:

    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <iterator>
    
    struct account {
        std::string acct;
        std::string fruit;
        std::string fruit2;
        double qty;
    
        friend std::ostream &operator<<(std::ostream &os, account const &a) {
            return os << a.acct << std::setw(10) 
                    << a.fruit << std::setw(10)
                    << a.fruit2 << std::setw(5)
                    << a.qty;
        }   
    };
    
    int main() { 
        account accts[] = {
            { "0000", "apples", "pears", 2.0 },
            { "0001", "oranges", "banana", 1.0 }
        };
    
        std::copy_n(accts, 2, std::ostream_iterator<account>(std::cout, "\n"));
    }
    

    产生的结果与任何理解setw 的人所期望的一致:

    0000    apples     pears    2
    0001   oranges    banana    1
    

    正如您在规范中所期望的那样,每个项目都在其字段中右对齐。

    【讨论】:

      【解决方案3】:

      您只是缺少 std::ios_base::left 标志。

      std::cout << std::setw(10) << std::setiosflags(std::ios_base::left)
            << "x" << "y" << std::endl;
      

      【讨论】:

        猜你喜欢
        • 2017-03-12
        • 1970-01-01
        • 1970-01-01
        • 2021-07-15
        • 2020-07-17
        • 2013-11-18
        • 2016-01-17
        • 1970-01-01
        • 2021-06-24
        相关资源
        最近更新 更多