|
|
|
|
|
|
|
The next input operation (for j) fails; an int value cannot begin with a decimal point. The cin stream is now in the fail state, and the current value of j (20) remains unchanged. The third input operation (for k) is ignored, as are all the rest of the statements in our program that read from cin. |
|
|
|
|
|
|
|
|
Another way to make a stream enter the fail state is to try to open an input file that doesn't exist. Suppose that you have a data file on your disk named myfile.dat. In your program you have the following statements: |
|
|
|
|
|
|
|
|
ifstream inFile;
inFile.open(myfil.dat);
inFile >> i >> j >> k; |
|
|
|
|
|
|
|
|
In the call to the open function, you misspelled the name of your disk file. At run time, the attempt to open the file fails, so the stream inFile enters the fail state. The next three input operations (for i, j, and k) are null operations. Without issuing any error message, the program proceeds to use the (unknown) contents of i, j, and k in calculations. The results of these calculations are certain to be puzzling. |
|
|
|
|
|
|
|
|
The point of this discussion is not to make you nervous about I/O but to make you aware. The Testing and Debugging section at the end of this chapter offers suggestions for avoiding input failure. And in Chapters 5 and 6, you will learn about program statements that let you test the state of a stream. |
|
|
|
|
|
|
|
|
Over the last two chapters and the first part of this one, we have introduced elements of the C++ language that let us input data, perform calculations, and output results. The programs we wrote were short and straightforward because the problems to be solved were simple. We are ready to write programs for more complicated problems, but first we need to step back and look at the overall process of programming. |
|
|
|
|
|
|
|
|
As you learned in Chapter 1, the programming process consists of a problem-solving phase and an implementation phase. The problem-solving phase includes analysis (analyzing and understanding the problem to be solved) and design (designing a solution to the problem). Given a complex problemone that results in a 10,000-line program, for exampleit's simply not reasonable to skip the design process and go directly to writing C++ code. What we need is a systematic way of designing a solution to a problem, no matter how complicated the problem is. |
|
|
|
|
|
|
|
|
In the remainder of this chapter, we describe two important methodologies for designing solutions to more complex problems: top-down design |
|
|
|
|
|