< previous page page_176 next page >

Page 176
Another oversight, one that doesn't cause input failure but causes programmer frustration, is to use cin or cout in an I/O statement when you meant to specify a file stream. If you mistakenly use cin instead of an input file stream, the program stops and waits for input from the keyboard. If you mistakenly use cout instead of an output file stream, you get unexpected output on the screen.
By giving you a framework that can help you organize and keep track of the details involved in designing and implementing a program, top-down design (and, later, object-oriented design) should help you avoid these errors in the first place.
In later chapters, you'll see that you can test modules separately. If you make sure that each module works by itself, your program should work when you put all the modules together. Testing modules separately is less work than trying to test an entire program. In a smaller section of code, it's less likely that multiple errors will combine to produce behavior that's difficult to analyze.
Testing and Debugging Hints
1. Input and output statements always begin with the name of a stream variable, and the >> and < operators point in the direction in which the data is going. The statement
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
cout << n;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
sends data to the output stream cout, and the statement
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
cin >> n;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
sends data to the variable n.
2. When a program inputs from or outputs to a file, be sure each I/O statement from or to the file uses the name of the file stream, not cin or cout.
3. When you open a data file for input, make sure that the parameter to the open function supplies the correct name of the file as it exists on disk.
4. Be sure that each input statement specifies the correct number of variables and that each of those variables is of the correct data type.
5. If your input data is mixed (character and numeric values), be sure to deal with intervening blanks.
6. Echo-print the input data to verify that each value is where it belongs and is in the proper format. (This is crucial because an input failure in C++ doesn't produce an error message or terminate the program.)

 
< previous page page_176 next page >