2

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?

user2802557
  • 747
  • 1
  • 9
  • 19
  • 1
    What "compile time errors"? When you receive an error message, please post it. – Philipp Jun 18 '15 at 14:50
  • Duplicate: http://stackoverflow.com/questions/10356300/is-it-possible-to-pass-cout-or-fout-to-a-function – acraig5075 Jun 18 '15 at 14:54
  • Also, what "combination of references or pointers" did you use? As you can see from the answers given, the code works correctly when using a reference parameter. – PaulMcKenzie Jun 18 '15 at 14:54

3 Answers3

5

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

Pass it by reference instead:

void writeToStream(std::stringstream &sstr)
Andreas DM
  • 10,685
  • 6
  • 35
  • 62
4

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();
}
Community
  • 1
  • 1
Tyler Jandreau
  • 4,245
  • 1
  • 22
  • 47
2

Change your function as follows and include <sstream>

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

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

Steephen
  • 14,645
  • 7
  • 40
  • 47