#include #in...">

"Off by one error" when using istringstream in C ++

I get 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 the last "you" token twice, but if I make the following changes, everything works fine.

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

Can someone explain to me how the while loop works. Thanks

+4
source share
1 answer

It is right. The while(iss) condition fails only after you read the end of 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 are trying 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 reason, you should always use the second approach that you show. In this approach, the loop will not be entered if the reading has not been completed.

+9
source

Source: https://habr.com/ru/post/1392623/


All Articles