1

以下代码:

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语句之后没有结束?

4

2 回答 2

2

You may modify your program like

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

Your code is not working because in the third iteration, the read was fine and didn't set the fail flag, it is set when the read is unsuccessful i.e. when it tries to in the 4th iteration.

As the read failed, the buffer still has the old values, which are printed(fail now returns true in 5th iteration as it failed in 4th)

于 2013-08-17T09:31:09.120 回答
1

因为它没有失败,就这么简单。读取成功,但您犯了错误检查错误为时已晚。

在使用读入的对象之前,您必须检查fail条件,否则您将面临处理无效数据的风险。你可以这样写循环:

while (1) {
    ss >> temp >> ch >> temp1;
    if (ss.fail()) break;
    cout << temp << ":" << temp1 << endl;
}

但惯用的做法是在@Shaksham 的回答中。

于 2013-08-17T09:56:53.017 回答