Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting width in C++ output stream

Tags:

c++

width

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.

like image 775
Andre Manoel Avatar asked Aug 30 '11 19:08

Andre Manoel


1 Answers

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;
like image 67
Jason Avatar answered Oct 21 '22 01:10

Jason