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 );
}
Output for above program is coming in this format "some_value::" I have also tried ss.str(std::string()) and ss.str().clear() but even that doesn't work. Could somebody please suggest any ways how to tackle this problem?
You've correctly emptied the string buffer with ss.str("")
, but you also need to clear the stream's error state with ss.clear()
, otherwise no further reads will be attemped after the first extraction, which led to an 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 full code and you do not need the individual variables for any reason, I'd do this:
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's much simpler. See it working here.
In C++11 you can avoid the stream altogether using std::to_string
, but that doesn't allow you to zero-pad.
You need to call the clear method of the stringstream rather than on the string returned by the stringstream 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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With