在C ++输出流中设置宽度 [英] Setting width in C++ output stream

查看:127
本文介绍了在C ++输出流中设置宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过设置不同字段的宽度,在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;问题是,这两个选项都不允许我设置一个默认的最小宽度,而我必须设置一个默认的最小宽度。改变它每次我会写的东西流。



有没有人知道我可以做一个方法,而不必重复同样的呼叫无数次?
提前感谢。

解决方案

您可以创建一个重载运算符< 并包含一个 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&运算符<<(const T& output)
{
stream_obj< setw(width)<<输出;

return * this;
}

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

现在可以像下面这样调用:

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


I'm trying to create a neatly formatted table on C++ by setting the width of the different fields. I can use setw(n), doing something like

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

or change ios_base::width

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

The problem is, neither of the alternatives allows me to set a default minimum width, and I have to change it everytime I'll write something to the stream.

Does anybody knows a way I can do it without having to repeat the same call countless times? Thanks in advance.

解决方案

You can create an object that overloads operator<< and contains an iostream object that will automatically call setw internally. For instance:

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;
        }
};

You can now call it like the following:

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

这篇关于在C ++输出流中设置宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆