“Off by one error” while using istringstream in C++

怎甘沉沦 提交于 2019-12-10 16:03:15

问题


I get an off by one error while executing the following code

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

}

It prints out the last token "you" twice, However if I make the following changes everything works fine.

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

Can anyone explain me how is the while loop operating. Thanks


回答1:


That is correct. The condition while(iss) fails only after you read past the end of the stream. So, after you have extracted "you" from your stream, it will still be true.

while(iss) { // true, because the last extraction was successful

So you try to extract more. This extraction fails, but does not affect the value stored in tokens, so it is printed again.

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

For this very reason, you should always use the second approach you show. In that approach, the loop will not be entered, if the read was unsuccessful.



来源:https://stackoverflow.com/questions/8983079/off-by-one-error-while-using-istringstream-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!