I'm getting funny results using stringstream within a for loop.
I have 2 for loops looping through a 2D vector of Tiles (I'm making a tile engine for a game). I want to display a string over each tile that shows its 2d vector indexes. Since c++ and SFML don't have a simple method of concatenating strings with other data types (like fprint) I have to use a stringstream and set that as my sf::String text.
Scenario 1 works the way I'm intending: Setting sf::String's text to "test" without using stringstream. This displays 1 word "test" over each tile.
Scenaria 2's result is unexpected: Setting stringstream to "test" and setting sf::String's text to stringstream.str() display 1 "test" on the first tile, 2 "test"s on the second, 3 on the third, etc until it's all a jumbled mess.
I run into this too when I come back to using stringstream. All of the data you insert into a stringstream doesn't get removed when you call the str() member. You need to clear it out when you want to add new items:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <ssstream>
sf::String tileString;
stringstream ss;
ss << "test";
tileString.SetText( ss.str() );
ss.str( "" ); /* Clear out ss */
Since you keep adding to the stringstream every iteration of your for loops where you encounter a "tile", it's doing exactly what you tell it to. Nothing weird about it.
clear(), as it relates to streams, resets the error states.
Assuming this is simplified code and you actually have a reason to be using a stringstream, try this:
Without calling both there is the possibility of one iteration doing something that can affect the other iterations. That is, there are dependencies that are not obvious when using streams.