Why read the file first and then check it?

I am simply reviewing my exams and cannot look back at the following provided by our lecturer:

When opening fstream, check if you opened or not

  • Then read before checking for input_file.fail ()

  • If you checked before reading, you may additional unwanted input

It makes no sense for me to read first, should I check first?

If anyone can explain, I will be very grateful :)

+6
source share
1 answer

input_file.fail() determines whether any previous operations have occurred, and whether the upcoming operation will occur. Therefore, if you write this:

 if (!input_file.fail()) { int value; input_file >> value; /* ... process value ... */ } 

Then, after reading the value , you have no idea whether you really read something or not. All you know is that right before reading, everything works correctly. It is possible that you could not read the integer, either because you were at the end of the file, or the data in the file were not integers.

On the other hand, if you write

 int value; input_file >> value; if (!input_file.fail()) { /* ... process value ... */ } 

Then you try to read. If this succeeds, then you will process the value you read. If not, you can react to the fact that the last operation failed.

(You can be even prettier:

 int value; if (input_file >> value) { /* ... process value ... */ } 

which combines read and test operations into one. It is much clearer here that you confirm that the reading succeeded.)

If you are doing a loop reading, a very simple way to do this is:

 for (int value; input_file >> value; ) { /* ... process value ... */ } 

This makes it clear that you are executing a loop while you can continue to read values ​​from the file.

Hope this helps!

+10
source

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


All Articles