c++ - 无法用新值覆盖 stringstream 变量

标签 c++ 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() 但即使这样也行不通。 有人可以建议任何解决此问题的方法吗?

最佳答案

你已经 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/

相关文章:

c++ - 具有初始化列表的类启动 std::array 成员变量

c++ - 如何修复丢失的 qt 小部件库 makefile 链接?

c++ - 在 C++ 中对排列进行排序的最便宜的方法是什么?

c++ - std::stringstream 与 std::string 用于连接多个字符串

c++ - 防止为字符串流提取运算符 (>>) 不支持的类型实例化模板类

python - PyThreadState_GET() 从 PyImport_GetModuleDict() 中返回 NULL

c++ - 如何从一个字符串中提取多个子字符串?

c++ - stringstream setprecision 和浮点格式

c++ - Ho 得到一个字符串,直到一个字符的最后一次出现

c++ - 如何返回 gmock 中的输入参数之一