You have correctly emptied the string buffer using ss.str("") , but you also need to clear the stream error state using ss.clear() , otherwise there will be no further reads after the first extraction, which led to the EOF condition.
So:
string whatTime(int seconds) { string h,m,s,ans; stringstream ss; ss << (seconds/3600); seconds -= (3600*(seconds/3600)); ss >> h; ss.str(""); ss.clear(); ss << (seconds/60); seconds -= (60*(seconds/60)); ss >> m; ss.str(""); ss.clear(); ss << seconds; ss >> s; return (h + ":" + m + ":" + s ); }
However, if this is your complete code and you do not need separate variables for any reason, I would do the following:
std::string whatTime(const int seconds_n) { std::stringstream ss; const int hours = seconds_n / 3600; const int minutes = (seconds_n / 60) % 60; const int seconds = seconds_n % 60; ss << std::setfill('0'); ss << std::setw(2) << hours << ':' << std::setw(2) << minutes << ':' << std::setw(2) << seconds; return ss.str(); }
It is much simpler. See how it works here .
In C ++ 11, you can generally avoid the stream by using std::to_string , but this does not allow you to reset to zero.
source share