以下代码:
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/