9

I have a stringstream object and I am wondering how to reset it.

stringstream os;
for(int i = 0; i < 10; ++i){
        value = rand() % 100;
        os<<value;
        cout<<os.str()<<" "<<os<<endl;
        ntree->insert(os.str());
        //I want my os object to be reset here
    }
leiyc
  • 903
  • 11
  • 23
realtekme
  • 353
  • 4
  • 6
  • 16

3 Answers3

13

If you want a new ostringstream object each time through the loop, the obvious solution is to declare a new one at the top of the loop. All of the ostream types contain a lot of state, and depending on context, it may be more or less difficult to reset all of the state.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • 1
    That would also mean that it would be better encapsulated inside the scope of the loop, which is always good :) (See "Item 26: Postpone variable definitions as long as possible." in Scott Meyers' "Effective C++" – Svend Hansen Jul 19 '13 at 10:43
9

If you want to replace the contents of the stringstream with something else, you can do that using the str() method. If you call it without any arguments it will just get the contents (as you're already doing). However, if you pass in a string then it will set the contents, discarding whatever it contained before.

E.g.:

std::stringstream os;
os.str("some text for the stream");

For more information, check out the method's documentation: http://www.cplusplus.com/reference/sstream/stringstream/str

Peter Bloomfield
  • 5,578
  • 26
  • 37
0

Your question is a bit vague but the code example makes it clearer.

You have two choices:

First, initialze ostringstream through construction (construct another instance in each step of the loop):

for(int i = 0; i < 10; ++i) {
    value = rand() % 100 ;
    ostringstream os;
    os << value;
    cout << os.str() << " " << os << endl;
    ntree->insert(os.str());
    //i want my os object to initializ it here
}

Second, reset the internal buffer and clear the stream state (error state, eof flag, etc):

for(int i = 0; i < 10; ++i) {
    value = rand() % 100 ;
    os << value;
    cout << os.str() << " " << os << endl;
    ntree->insert(os.str());
    //i want my os object to initializ it here
    os.str("");
    os.clear();
}
utnapistim
  • 26,809
  • 3
  • 46
  • 82
  • Clearing the stream's state is anything but trivial: in the most general case, you also have to reinitialize the `fmtflag`, the precision, the fill character, and any state dynamically allocated by `xalloc`. (That last is very, very difficult.) – James Kanze Jul 19 '13 at 11:28