我在执行以下代码时因一个错误而关闭
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main (int argc, char* argv[]){
string tokens,input;
input = "how are you";
istringstream iss (input , istringstream::in);
while(iss){
iss >> tokens;
cout << tokens << endl;
}
return 0;
}
它打印出最后一个标记“you”两次,但是如果我进行以下更改,一切正常。
while(iss >> tokens){
cout << tokens << endl;
}
谁能解释一下 while 循环是如何运行的。谢谢
最佳答案
没错。条件while(iss)
仅在您读取到流的末尾之后 失败。因此,在您从流中提取 “you”
之后,它仍然是 true。
while(iss) { // true, because the last extraction was successful
所以你尝试提取更多。此提取失败,但不影响存储在 tokens
中的值,因此再次打印。
iss >> tokens; // end of stream, so this fails, but tokens sill contains
// the value from the previous iteration of the loop
cout << tokens << endl; // previous value is printed again
正是出于这个原因,您应该始终使用您展示的第二种方法。在这种方法中,如果读取不成功,则不会进入循环。
关于c++ - 在 C++ 中使用 istringstream 时出现 "Off by one error",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8983079/