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;
s1 >> i_minute;
s2 >> i_second;`
ss >> i_hour;
ss << minute;
ss >> i_minute;
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.clear(); ss.str(minute); ss >> i_minute;