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 );
}
Run Code Online (Sandbox Code Playgroud)
以上程序的输出以这种格式"some_value ::"我也尝试过ss.str(std :: string())和ss.str().clear(),但即使这样也行不通.有人可以建议如何解决这个问题吗?
Lig*_*ica 11
您已正确清空字符串缓冲区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 );
}
Run Code Online (Sandbox Code Playgroud)
但是,如果这是您的完整代码,并且由于任何原因您不需要单个变量,我会这样做:
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();
}
Run Code Online (Sandbox Code Playgroud)
它简单得多.看到它在这里工作.
在C++ 11 ,你可以完全避免流使用std::to_string,但是,这并不让你零垫.