【问题标题】:"Off by one error" while using istringstream in C++在 C++ 中使用 istringstream 时“关闭一个错误”
【发布时间】:2012-02-17 11:28:31
【问题描述】:

在执行以下代码时,我得到了一个错误

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

}

它会打印出最后一个标记“你”两次,但是如果我进行以下更改,一切正常。

 while(iss >> tokens){
    cout << tokens << endl;
}

谁能解释一下while循环是如何运作的。谢谢

【问题讨论】:

    标签: c++ istringstream


    【解决方案1】:

    没错。条件while(iss) 仅在读取到流末尾之后 失败。因此,在您从流中提取 "you" 之后,它仍然是正确的。

    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
    

    出于这个原因,您应该始终使用您展示的第二种方法。在这种方法中,如果读取不成功,则不会进入循环。

    【讨论】:

      猜你喜欢
      • 2017-08-23
      • 2019-04-28
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 2022-01-13
      • 2019-12-31
      • 2014-09-13
      相关资源
      最近更新 更多