0

I'm using the following two different snippets of code to take the input of multiple numbers from the same line:

Snippet1:

int input {0};
while(cin >> input){
   cout << "Read: " << input << endl;
   if(cin.eof())
       break;
}

Snippet2:

int input {0};
string str {NULL};
getline(cin, str);
istringstream ss {str};
while(ss >> input ){
   cout << "Read: " << input << endl;
   if(ss.eof())
            break;
}

Input I'm using:

1 2 3 4 5

Output:

Read: 1
Read: 2
Read: 3
Read: 4
Read: 5

In both the codes I am able to read the numbers from the input, however in snippet 1 the loop doesn't exit even after printing all the numbers. Which means that cin.eof() doesn't return true even after there's nothing to be read from the input stream and thus the loop goes on. This problem however is not arising when I'm using istringstream - the loop terminates after printing the numbers. Can anyone explain why is this so? Both are text streams right? So why the difference in behaviour?

Biwadeep
  • 31
  • 4
  • Please could you provide your test cases? The lines or the file contents that you use to test – Pat. ANDRIA Mar 07 '21 at 14:33
  • just because you stop writing in the console that doesn't mean its the end of the console input – Alan Birtles Mar 07 '21 at 14:36
  • @AlanBirtles can you please explain what you mean? Shouldn't the point where we stop writing in the console, be the end of console input? What else happens otherwise? – Biwadeep Mar 07 '21 at 14:41
  • If that's an interactive console, you have to explicitly signal eof, ^D on unix, ^Z on windows. –  Mar 07 '21 at 14:46
  • When you stop writing in the console how would the console know that you are never going to write anything else? Unless you send some platform specific key combination to end the consollle stream it will never reach eof – Alan Birtles Mar 07 '21 at 14:50
  • @Alan Birtles thank you for your answer. I'm new to C++, did not know this fact... – Biwadeep Mar 07 '21 at 14:55
  • 1
    Does this answer your question? [How to terminate reading from cin?](https://stackoverflow.com/questions/19991729/how-to-terminate-reading-from-cin) – Pat. ANDRIA Mar 07 '21 at 14:57
  • 1
    @Pat.ANDRIA Yes thank you. – Biwadeep Mar 07 '21 at 15:13

0 Answers0