c++ - 为什么即使在 'ss.fail()' 为真(这里 'ss' 是一个 stringstream 对象)之后循环也不终止?

标签 c++ stringstream

以下代码:

int main() {
    stringstream ss;
    string str;
    str = "999:97 42:22 44:102300";
    ss << str;
    char ch;
    int temp, temp1;
    while (1) {
        if (ss.fail()) {
    break;
    }
    ss >> temp >> ch >> temp1;
    cout << temp << ":" << temp1 << endl;
    }
    return 0;
}

这给出了以下输出:

999:97
42:22
44:102300
44:102300

这里还有一个链接:http://ideone.com/cC75Sk

我只是想知道,为什么代码在 break 语句之后没有结束?

最佳答案

你可以像这样修改你的程序

int main() 
{
    stringstream ss;
    string str;
    str = "999:97 42:22 44:102300";
    ss << str;
    char ch;
    int temp, temp1;
    while (ss >> temp >> ch >> temp1) 
    {
        cout << temp << ":" << temp1 << endl;
    }
    cin.ignore();
}

您的代码不工作,因为在第三次迭代中,读取正常并且没有设置失败标志,它在读取不成功时设置,即当它在第四次迭代中尝试时设置。

由于读取失败,缓冲区仍然有旧值,这些值被打印出来(失败现在在第 5 次迭代中返回 true,因为它在第 4 次迭代中失败)

关于c++ - 为什么即使在 'ss.fail()' 为真(这里 'ss' 是一个 stringstream 对象)之后循环也不终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18287135/

相关文章:

C++ stringstream 输入的各种结果

c++ - 为什么在我的代码中删除 ostringstream 对象会导致段错误?

c++ - 从函数 C++ 返回 float 组

c++ - 构造函数/函数声明参数列表中的统一初始化

c++ - 内置类型(int、char 等)的析构函数

c++ - 使用 CRTP 时如何获取模板参数的大小?

c++ - 是否可以为通用元素列表创建排序?

c++ - 使用 openmode ios_base::out 的 istringstream 有什么意义

c++ - 为什么使用空字符串流会产生依赖于编译器优化的结果

c++ - 从 stringstream 中删除 char 并附加一些数据