不能用新值覆盖stringstream变量 [英] cannot overwrite stringstream variable with a new value

查看:209
本文介绍了不能用新值覆盖stringstream变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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(),但即使这不工作。
有人可以建议任何解决这个问题的方法吗?

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?

推荐答案

正确地清空了 ss.str()的字符串缓冲区,但您还需要使用 ss.clear()清除流的错误状态,否则在第一次提取后不会再进行进一步的读取,从而导致EOF条件。

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.

因此:

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

更简单。 请参见此处

在C ++ 11中您可以使用 std :: to_string ,但这不允许你填零。

In C++11 you can avoid the stream altogether using std::to_string, but that doesn't allow you to zero-pad.

这篇关于不能用新值覆盖stringstream变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆