C++ Using stringstream after << as parameter

后端 未结 5 1578
Happy的楠姐
Happy的楠姐 2021-01-02 19:20

Is it possible to write a method that takes a stringstream and have it look something like this,

void method(string st         


        
5条回答
  •  盖世英雄少女心
    2021-01-02 20:12

    Ah, took me a minute. Since operator<< is a free function overloaded for all ostream types, it doesn't return a std::stringstream, it returns a std::ostream like you say.

    void printStringStream(std::ostream& ss)
    

    Now clearly, general ostreams don't have a .str() member, but they do have a magic way to copy one entire stream to another:

    std::cout << ss.rdbuf();
    

    Here's a link to the full code showing that it compiles and runs fine http://ideone.com/DgL5V

    EDIT

    If you really need a string in the function, I can think of a few solutions:

    First, do the streaming seperately:

    stringstream var;
    var << "Text" << intVar << "More text"<

    Second: copy the stream to a string (possible performance issue)

    void printStringStream( ostream& t)
    {
        std::stringstream ss;
        ss << t.rdbuf();
        method(ss.str());
    }
    

    Third: make the other function take a stream too

提交回复
热议问题