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() 但即使这样也不起作用。
有人可以建议任何方法来解决这个问题吗?
You've 正确地 https://stackoverflow.com/a/2848109/560648清空字符串缓冲区ss.str("")
,但您还需要清除流的错误状态ss.clear()
,否则在第一次提取后将不会尝试进一步读取,这会导致 EOF 条件。
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 );
}
但是,如果这是您的完整代码并且您出于任何原因不需要各个变量,我会这样做:
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();
}
简单多了。在这里查看它的工作情况 http://ideone.com/pZ1jX2.
在 C++11 中你可以完全避免流 https://stackoverflow.com/questions/8065413/stdlexical-cast-is-there-such-a-thing using std::to_string
,但这不允许您进行零填充。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)