Search code examples
c++stringstream

Pass a Stringstream into a method


What I want to do is create a method that takes a stringstream as a parameter, write to it in the method, then read from the stringstream outside of the method.

For example something like this.

void writeToStream(std::stringstream sstr){
   sstr << "Hello World";
}

int main(){
   std::stringstream sstr;
   writeToStream(sstr);
   std::cout << sstr.str();
}

I am getting compile time errors though when I do this. It might be because I am supposed to be using a reference to the stringstream or something like that. I have tried different combinations of using references or pointers but nothing seems to work?


Solution

  • std::stringstream cannot be copied how you have it written for your function. This is because of reasons discussed here. You can, however, pass the std::stringstream as a reference to your function, which is totally legal. Here is some example code:

    #include <sstream>
    
    void writeToStream(std::stringstream &sstr){
       sstr << "Hello World";
    }
    
    int main(){
       std::stringstream sstr;
       writeToStream(sstr);
       std::cout << sstr.str();
    }