how to reset stringstream object

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 } 
+8
c ++ stringstream
source share
3 answers

If you need a new ostringstream object every time through the loop, the obvious solution is to declare a new one at the top of the loop. All ostream types contain many states and, depending on the context, can be more or less difficult to reset the entire state.

+12
source share

If you want to replace the contents of stringstream with something else, you can do this using the str() method. If you call it without any arguments, it will just get the contents (as you already do). However, if you pass the string, then it will set the content, discarding everything that was previously contained.

eg:.

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

For more information, see the documentation for the method: http://www.cplusplus.com/reference/sstream/stringstream/str

+8
source share

Your question is a bit vague, but the sample code makes it more clear.

You have two options:

Initialize ostringstream first through the construct (build another instance at 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 } 

Secondly, 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(); } 
0
source share

All Articles