|
From: <jar...@ig...> - 2002-11-26 10:39:01
|
On 26 Nov, Olu...@ao... wrote:
> I want to write a function that will validate my C++ prgram. I want the
> function to display a message if wrong value type is entered. For example -
>
> int number1;
> cout << " Enter your number. The number must be between 1 and 4: " ;
> cin >> number1;
>
> if the user enter, a char value instead of a int value, i want the function
> to display a message of violation of variable type.
>
> Is it possible to write this type of function and what is the syntax.
>
You can do the following
after
cin >> number1;
if ( ! cin ) { // something went wrong, for interactive input
// most probably a format error
cin.clear(); // clear the error condition
cin.ignore(10000,'\n'); // ignore upto the end of line (upto 10000 chars)
cerr << "invalid input - please try again ";
cin >> number1;
}
if writing a loop around this, don't forget to offer another exit to
terminate the program.
--
Helmut Jarausch
Lehrstuhl fuer Numerische Mathematik
Aachen University
D 52056 Aachen, Germany
|