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 );
}
上述程序的输出格式为“some_value::” 我也尝试过 ss.str(std::string()) 和 ss.str().clear() 但即使这样也行不通。 有人可以建议任何解决此问题的方法吗?
最佳答案
你已经 correctly使用 ss.str("")
清空字符串缓冲区,但您还需要使用 ss.clear()
清除流的错误状态,否则不会进行进一步的读取在第一次提取后尝试,这导致了 EOF 条件。
所以:
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 );
}
但是,如果这是您的完整代码并且您出于任何原因不需要单个变量,我会这样做:
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();
}
要简单得多。 See it working here .
在 C++11 中 you can avoid the stream altogether使用 std::to_string
,但这不允许您进行零填充。
关于c++ - 无法用新值覆盖 stringstream 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13891856/