Setting width in C++ output stream

后端 未结 3 768
情深已故
情深已故 2020-12-05 11:02

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 << set         


        
相关标签:
3条回答
  • 2020-12-05 11:27

    I know this is still making the same call, but I know of no other solution from what I am getting from your question.

    #define COUT std::cout.width(10);std::cout<<
    
    int main()
    {
        std::cout.fill( '.' );
    
        COUT "foo" << std::endl;
        COUT "bar" << std::endl;
    
        return 0;
    }
    

    Output:

    ..........foo
    ..........bar
    
    0 讨论(0)
  • 2020-12-05 11:45

    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;
    
    0 讨论(0)
  • 2020-12-05 11:48

    why not just create a function?

    pseudocode e.g.

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

    That's a bit scrappy but hopefully you get the idea.

    0 讨论(0)
提交回复
热议问题