easy one, i hope, in a simple program, where the user is requested to input a number (stored as an int), if the user accidentally inputs a letter the console crashes instantly, how would I prevent the prog from crashing if a letter was accidentally entered intead of an int?
I'm using visual C++ express 2008.
thanks spaggy, but how do I implement this? forgive me I am very fresh to C++, the bool good(); looks like it will do the job alright, how would I implement this in the code?
e.g. int number;
cout << "please enter a number" << endl;
cin >> number;
how do I implement bool good() here as to flag if a letter is incorrectly entered as an int?
Ok tried this in a quick test (code below) and it still fails, compiles fine but when I enter a letter the console screen crashes (loops continuously)? Have I implemented this correctly? whould this detect the error in a letter being entered?
1 2 3 4 5 6 7 8 9 10 11 12 13
//test
cout << endl << "please enter a number " << endl;
int number;
cin >> number;
if (cin.good())
{
cout << endl << number << endl;
}
else
cout << "you need to enter a number" << endl;
}
quick update, the above code actually works ok if I run one time, however if I try to loop and request a number a second time ot continually loops (doesnt seem to execute the cin again.
I have written some simple code below (probably over complex), the intent here is to request an input number, check that a number is input (if a letter instead of a number is input it should request a number again). Now when this code is executed it works of for a number but when I input a letter it just loops without again prompting for a number? Can anyone explain why this is?
Thanks.