Lab 3 3 Understanding Input Failure
Lab 3 3 Understanding Input Failure
Many things can go wrong during program execution. Even a program that is syntactically
correct might produce incorrect results. For example, what would happen if you tried to
input a letter into an int variable? If the input data did not match the corresponding
variables, the program would run into problems. Attempting to read a letter into an int or
double variable would result in an input failure. Consider the following statements:
int a, b, c;
double x;
If the input is:
W 54
then the statement:
cin >> a >> b;
would result in an input failure, because you are trying to input the character ‘W’ into the
int variable a. If the input were:
35 67.93 48
then the input statement:
cin >> a >> x >> b;
would result in storing 35 in a, 67.93 in x, and 48 in b.
Now consider the following statement with the previous input (the input with three values):
cin >> a >> b >> c;
This statement stores 35 in a and 67 in b. The reading stops at . (the decimal point). Because
the next variable c is of the data type int, the computer tries to read . into c, which is an
error. The input stream then enters a state called the fail state.
What actually happens when the input stream enters the fail state? Once an input stream
enters a fail state, all further I/O statements using that stream are ignored. Unfortunately,
the program quietly continues to execute with whatever values are stored in variables and
produces incorrect results. You can use the stream function clear to restore the input
stream to a working state. The syntax to use the function clear is:
istreamVar.clear();
Objectives
In this lab, you become familiar with input failure, the fail state, and how to detect and
recover from that state.
6a. Critical Thinking Exercise: Below is the code for inputFailure.cpp, which is saved in the
Chap03 folder of your Student Data Files.
cout << “Line 11: cin = “ << cin << endl; //Line 11
cout << “Line 12: cin.fail() returns “ << cin.fail() << endl;
//Line 12
cout << “Line 13: Now we will use cin.clear().” << endl;
//Line 13
cin.clear(); //Line 14
cout << “Line 15: cin = “ << cin << endl; //Line 15
cout << “Line 16: cin.fail() returns “ << cin.fail();
//Line 16
return 0;
}
Compile, link, and execute inputFailure.cpp. Use 34 K 67 28 as the input values. Write
the output that the program generates in the following space.
6b. What are the three values of the cin variable shown by your program?
6c. What are the two return values of the function fail shown by your program?
6d. Analyze the output of your program and your answers to questions 6b and 6c. Now
answer the following questions using your own words: What happens to the stream
variable cin after an input failure? What happens to the stream variable cin after
using the function clear? How can you use the function fail to determine if an input
failure has occurred?