Pass a Stringstream into a method

2.9k views Asked by At

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?

3

There are 3 answers

0
Tyler Jandreau On BEST ANSWER

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();
}
0
Steephen On

Change your function as follows and include <sstream>

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

Demo: http://coliru.stacked-crooked.com/a/34b86cfbd3cf87fc

0
Andreas DM On

You can't copy a stream, therefore you can't pass it by value.

Pass it by reference instead:

void writeToStream(std::stringstream &sstr)