c++ - 在 C++ 中使用 istringstream 时出现 "Off by one error"

标签 c++ istringstream

我在执行以下代码时因一个错误而关闭

#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/

相关文章:

C++:无法使用字符串流操作打开文件

c++ - istringstream 不改变 C++

c++ - 使用通配符计算下一个最近的日期时间匹配

c++ - 使用 setjmp 和 longjmp 时 Valgrind 失败

c++ - 从通用函数/lambda 推导出函数参数

c++ - OpenCV cv::imshow() GUI 未显示

c++ - operator>> 可以读取 int hex AND decimal 吗?

c++ - 查找istringstream中有多少个字符串

c++ - 如何阻止读取 C++ stringstream 以等待数据

c++ boost计算函数花费的时间