While (cin >> x) and file ending issues

I am a little confused as to what is happening, I play with some programs from "Accelerated C ++", and hit the problem with one of the early programs (page 35, if you were lucky to have a copy nearby).

He uses this snippet:

while (cin >> x) {
   ++count;
   sum += x;
}

("count" is an integer, "x" is a double)

It works as intended, allowing me to enter several values ​​and add them together, but I cannot understand what is happening with the "End-of-file" signature. The book says that the loop will continue to work until the program encounters the end-of-file signal, which is ctrl + z in windows.

Everything is fine and it works, but then my program will not allow me to use cin again. I usually just tweak the program to wait for some random variable to stop the closing console immediately after execution (is there a better way to do this, by the way?), Which, as I noticed, and I wonder if there is a solution. I did a bunch of searches, but found little that I didn’t say what was already said in the book (press ctrl + z or enter an incompatible input type, etc.)

I am using Visual Studio 2008 express to compile.

+3
source share
3 answers

From one point of view, as soon as you get to the end of the input stream, then by definition there is nothing left in the stream, so trying to read it again does not make sense.

" ", , , Ctrl-Z , , , cin. eof .

( ), clear.

std::cin.clear();

.

+7

EOF , STDIN ( cin) . , .

, , , , - , " ",.

+2

, ( , ). .

  • :
    • cmd. cd . .
      , .
  • ,
    • - .
      ( "" )
  • , reset .
    • i.e. If you type text that causes the operator → to fail, the error bit is set.
      You can reset the error bit cin.clear ()
      Perhaps this will not work if you close the stream with ctrl-Z
  • Please note if you try to use cin → pause; (where char pause or something else)
    Make sure the stream is empty using cin.ignore (), otherwise the pause will not happen. as the code will just keep reading data
+1
source

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


All Articles