Reputation: 353
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
}
Upvotes: 9
Views: 24417
Reputation: 5756
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
Upvotes: 9
Reputation: 27365
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();
}
Upvotes: 0
Reputation: 153899
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.
Upvotes: 13