Testing for Extraction Errors

It is very important to test for errors during the extraction process. Consider, for example, the statement:

cin >> n;

If n is a signed integer, then an input value of 33,000 (32,767 is the maximum allowed value) will set the stream's fail bit. If you don't deal with the error immediately, then cin will be unusable. All subsequent extractions result in an immedate return with no value stored.

Example 15

The error processing functions discussed under “Output Streams” apply also to input streams. Example 15 demonstrates how the fail and clear functions can be used with cin.

// exios115.cpp

#include <iostream.h>

int n[5], i;

void main()

{

cout << "Enter 5 values, separated by spaces" << endl;

for( i = 0; i < 5; i++ ) {

cin >> n[i];

if( cin.eof() || cin.bad() ) break; // Tests for end-of-file

// or unrecoverable error

if( cin.fail() ) { // Tests for format conversion error

cin.clear(); // Clear stream's fail bit

n[i] = 0; // and continue processing

}

}

for( i = 0; i < 5; i++ ) { // Prints the values just read

cout << n[i];

}

}