cannot overwrite stringstream variable with a new value

♀尐吖头ヾ 提交于 2019-12-07 08:17:02

问题


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?


回答1:


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.




回答2:


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

}



回答3:


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


来源:https://stackoverflow.com/questions/13891856/cannot-overwrite-stringstream-variable-with-a-new-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!