Why can't Iostream::eof be used in the loop?

Asked 2 years ago, Updated 2 years ago, 64 views

I heard that writing iostream::eof in a conditional sentence is a bad idea I usually write while(cin>>n) together and check EOF. But why can't I write iostream::eof myself and check it?

From C scanf("...,...)!What's the difference from writing in =EOF ?

c++ iostream

2022-09-22 14:58

1 Answers

This is because iostream::eof is set after reading the end of the stream (after the o occurs). I'll explain what this means in the next example.

while(!inStream.eof()){
    Accessing the //while statement means - not yet eof
    inStream >> data;
    // eof is now set -> data is not a valid value

    /* Data Processing -> error */
}

On the other hand, in the following situations:

while(inStream >> data){
  // The meaning of entering while means that read was successful (not eof)
  // If it fails, operator >> returns false and fails to enter while

  /* Data Processing -> ok */
}

It's safe because it is.

And for the second question,

if(scanf("...",...)!=EOF) = = if(!(inStream >> data).eof()) != != if(!inStream.eof()) inFile >> data

That's it. So scanf("...",...)!=EOF is a safe way to use.


2022-09-22 14:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.