【问题标题】:Setting width in C++ output stream在 C++ 输出流中设置宽度
【发布时间】:2023-03-05 21:25:01
【问题描述】:

我正在尝试通过设置不同字段的宽度在 C++ 上创建一个格式整齐的表格。我可以使用 setw(n),做类似的事情

cout << setw(10) << x << setw(10) << y << endl;

或更改 ios_base::width

cout.width (10);
cout << x;
cout.width (10);
cout << y << endl;

问题是,这两种方法都不允许我设置默认的最小宽度,而且我每次向流中写入内容时都必须更改它。

有没有人知道我可以做到这一点而不必无数次重复同一个电话? 提前致谢。

【问题讨论】:

标签: c++ width


【解决方案1】:

您可以创建一个重载operator&lt;&lt; 的对象并包含一个iostream 对象,该对象将在内部自动调用setw。例如:

class formatted_output
{
    private:
        int width;
        ostream& stream_obj;

    public:
        formatted_output(ostream& obj, int w): width(w), stream_obj(obj) {}

        template<typename T>
        formatted_output& operator<<(const T& output)
        {
            stream_obj << setw(width) << output;

            return *this;
        }

        formatted_output& operator<<(ostream& (*func)(ostream&))
        {
            func(stream_obj);
            return *this;
        }
};

您现在可以这样称呼它:

formatted_output field_output(cout, 10);
field_output << x << y << endl;

【讨论】:

  • +1,谢谢!万一其他人感兴趣:上面定义的第二个operator&lt;&lt; 允许该类处理诸如std::endl 之类的函数,如here 所述。希望这可以帮助任何其他好奇的猫正在分解@Jason 的代码......
【解决方案2】:

我知道这仍在打同样的电话,但我从您的问题中得到的信息没有其他解决方案。

#define COUT std::cout.width(10);std::cout<<

int main()
{
    std::cout.fill( '.' );

    COUT "foo" << std::endl;
    COUT "bar" << std::endl;

    return 0;
}

输出:

..........foo
..........bar

【讨论】:

  • 如果模板可以轻松制作,甚至允许输出链接,为什么还要使用宏?
【解决方案3】:

为什么不直接创建一个函数?

伪代码例如

void format_cout(text, w) {
 cout << text << width(w);
}

这有点草率,但希望你能明白。

【讨论】:

  • 这种方法很好也很简单,但它不允许你使用链式operator&lt;&lt;s。当您尝试使用std::endl...时,它也会导致(空白)问题...
猜你喜欢
  • 2016-09-06
  • 2013-10-01
  • 2015-06-30
  • 2011-03-30
  • 2013-09-06
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多