我从循环中的字符串流中提取值,每次循环执行时,都会重置循环顶部的字符串流。但是,每次在第二次迭代时,字符串的>>操作符都会失败。这个经过提炼的代码版本再现了我遇到的问题:
istringstream word;
string in;
int number;
while(cin >> in) {
word.str(in);
//Uncommenting either one of the following lines seems to solve the issue:
//word.clear();
//word.seekg(0);
word >> number;
if(word.fail()) {
cerr << "Failed to read int" << endl;
return 1;
}
cout << in << ' ' << number << endl;
}目前,它总是在第二次循环迭代中失败。但是,不注释这两行注释中的任何一行代码都解决了这个问题。我不明白的是,既然我已经用word.str(in)重置了字符串流,为什么它仍然失败呢?为什么重置get位置可以解决这个问题?
我是不是漏掉了弦乐的作用?它是否将eofbit标志设置在上一次有效的读取上,而不是在由于EOF而失败的读取上?如果是这样的话,为什么seekg(0)似乎清除了这个标志,而重置了字符串流却没有?
发布于 2019-12-12 14:05:38
正如@SomeProgrammer杜德建议的那样:只需将istringstream移动到while循环中(您可以将其更改为for循环,以将in保存在循环中):
for (string in; cin >> in;)
{
istringstream word(in);
int number;
if (!(word >> number))
{
cerr << "Failed to read int" << endl;
return 1;
}
cout << in << ' ' << number << endl;
}这样就可以重新创建每个循环。
当你在做的时候,把number也移到里面(当然,除非你在循环之外使用它)。
https://stackoverflow.com/questions/59306179
复制相似问题