cannot overwrite stringstream variable with a new value

折月煮酒 提交于 2019-12-05 17:44:42
Lightness Races with Monica

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 );

}

You only need the stringstream, nothing else. All the rest 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();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!