Arūnas Arūnas - 1 month ago 11x
C++ Question

Clear and reuse a stringstream for multiple conversions

I was working on a Hacker Rank assignment and needed a way to convert a string to int and decided to use stringstream(my first time using it). Is there a way to somehow use the same declared stringstram(is that how you call it?) instead of creating new ones for each conversion? I tried using the .clear() function and it still didn't work.

How I did it:

stringstream s0(hour); // this is my way of converting string to int because stoi doesn't seem to work
s0 >> i_hour;
cout << i_hour << endl;
stringstream s1(minute);
s1 >> i_minute;
stringstream s2(second);
s2 >> i_second;`

and how I wanted to do it:

stringstream ss(hour);
ss >> i_hour;
ss << minute;
ss >> i_minute;

is there any way to do it similarly? Looks really messy to keep declaring new ones.


You can call the str(s) method to initialize an std::istringstream to a new string. You should use std::istringstream if all you're doing is converting from a string.

If the previous conversion resulted in an error you will also need clear(), to clear its error state.

So your example would be:

istringstream ss(hour);
ss >> i_hour;
ss >> i_minute;