如何对齐不同的加长输出C ++

时间:2014-08-28 23:27:41

标签: c++ io alignment console-application

我试图在此搜索很多帖子,我仍然无法弄清楚这一点。说我有一个循环,它从文本文件中读取行,然后在屏幕上显示它们。我希望每个数据都对齐,但问题是数据可能是不同的legnths,所以在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)需要非静态。我也尝试过左右,这也不起作用。

3 个答案:

答案 0 :(得分:0)

如果您使用std :: string:

,以下是我解决此问题的方法
cout << left << setw(10) << account << setw(10) << fruit << setw(10 + strlen(fruit2.c_str()) -  strlen(fruit.c_str())) << fruit2 << endl;   

将格式的字符串长度考虑在内。只要水果名称不会太长,就可以选择任意偏移(“草莓”代替“苹果”会打破格式

setw(10)

答案 1 :(得分:0)

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

#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

每个项目在其字段中都是右对齐的,就像您对规范的期望一样。

答案 2 :(得分:0)

你只是错过了std :: ios_base :: left标志。

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