Cannot overwrite stringstream variable with new value

string whatTime(int seconds) { string h,m,s,ans; stringstream ss; ss << (seconds/3600); seconds -= (3600*(seconds/3600)); ss >> h; ss.str(""); ss << (seconds/60); seconds -= (60*(seconds/60)); ss >> m; ss.str(""); ss << seconds; ss >> s; return (h + ":" + m + ":" + s ); } 

The output for the above program comes in this format "some_value ::" I also tried ss.str (std :: string ()) and ss.str (). Clear (), but even this does not work. Can anyone suggest any ways to solve this problem?

+4
source share
3 answers

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.

+10
source

You need to call the clear string method, not the string returned by the string stream, using ss.clear() .

 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 ); } 
+2
source

You only need a stream of lines, nothing more. Everything else is pure overhead.

 string whatTime(int seconds) { stringstream ss; ss << setFill('0'); ss << setw(2) << (seconds/3600) << ":" // hours << setw(2) << ((seconds / 60) % 60) << ":" // minutes << setw(2) << (seconds%60); // seconds return ss.str(); } 
0
source

All Articles