| Physics and Astronomy |
|
Back to top
On this page
Contents Appendix: A better input loopErrors when reading data from a fileScientific "number-crunching" programs often run as "batch jobs" in a queueing system and read their data from a file. If there's an error in the input file it can be very confusing (and hard to fix) if the program then runs (possibly for several days) and just produces the wrong answers at the end. Therefore our program should try to help our users diagnose such problems. However, in this case there is no point in havng a "try again" loop. The general approach is simple: 1. Check for invalid or missing inputFor example: if (mass <= 0 ) {
fprintf(stderr, "ERROR: negative mass: %g\n", mass);
exit(1);
}
Note how we have printed out the erroneous value, the problem may be that the user has missed out a number, or put in too many and the program is reading in the wrong number and this will help them find it. 2. Have a log fileAfter reading in the initial data we can print out our understanding of it to the log file. When encountering invalid data in a non-interactive program it's usually best to print a helpful error message and quit. A better loop when reading from standard inputA variation of the infinite for(;;) loop in the lecture allows us to improve our infinite loop to handle a non-obvious problem: what if our program isn't reading its input from a human being typing at a keyboard, but from a file on the computer or another program? This might happen if, for example, we put our program on the web. A sesnible approach is to give the user a few attempts but after that to fail in much the same way as above: Note again how missing out the test in the If it gets a little tedious to have the
if ( tries > 5 ) test inside every
input loop then a cleaner way is to put the test into a small wrapper
function and to use that as the test in the for() loop.
The nice thing about this is that our test function, which we have called
toomany() can handle the exit from the program:
|