Example of Input Error
#include "iostream.h"
int main()
{
int y;
cin >> y ;
if (cin.fail()) cout << "Data entered incorrectly." << endl;
cout << y << endl;
return 0;
}
Output:
w
Data entered incorrectly.
-536882292
#include "iostream.h"
int main()
{
int item = 0;
char garbage;
cout << "Enter a number: ";
cin >> item;
while(cin.fail()){
cin.clear();
cin >> garbage;
cout << "Invalid Entry! Try Again: ";
cin >> item;
}
cout << "The number is: " << item;
return 0;
}
Output 1:
Enter a number: 3
The number is: 3
Output 2:
Enter a number: y
Invalid Entry! Try Again: t
Invalid Entry! Try Again: 3
The number is: 3
Output 3:
Enter a number: 3.22
The number is: 3
Christopher Alvin
Last modified: Wed Sep 22 16:57:46 CDT 1999