C++ cout auto separator

后端 未结 7 1756
半阙折子戏
半阙折子戏 2020-12-13 17:36

I am wondering if there is way that std::cout automatically will insert some predefined value between printed sequences.

For example:

st         


        
7条回答
  •  隐瞒了意图╮
    2020-12-13 18:06

    Simple answer is No, however, you can roll your own...

    #include 
    #include 
    
    using namespace std;
    
    struct set_some_separator{
        set_some_separator(const char* sep) : _sep(sep)
        { };
    
        template 
        set_some_separator& operator<<(const T& v)
        {
            _str << v << _sep;
            return *this;
        }
    
        friend
        ostream& operator<<(ostream& os, const set_some_separator& s)
        { return os << s._str.str(); }
    
        const char* _sep;
        ostringstream _str;
    };
    
    int main()
    {
        cout << (set_some_separator(" ") << 2 << 3 << 33 << 45) << endl;
    }
    

    Okay the format of the cout is slightly different, hey-ho...

提交回复
热议问题