Reputation: 9204
int main()
{
unsigned short wC;
while(1)
{
cout << "Enter the Value"<<endl;
cin >> wC;
if(wC < 0 || wC > 3)
{
cout << "Wrong value, Please Enter again" << endl;
}
else break;
}// end of while
cout << "The value is : " << wC << endl;
}//end of main
In the above code, when I give value in range of short 0xffff
it work fine.
And comes out of loop and print the value only when user has given value for wC
in between 0 to 3 otherwise prompt message to Enter again and wait for user's input.
But if value entered for wC
is more than 0xffff
then it goes to Infinite Loop.
I think it is due to value still exist in input cin
buffer or what?
Please help and provide some solution(hint), so that it should work.
NOTE : User is free to give any integer value. the code has to filter it out.
Using g++
compiler on Ubuntu/Linux
... and sizeof(unsigned short int) = 2 bytes
Upvotes: 1
Views: 231
Reputation: 71909
If input fails, either because what you entered isn't an integer at all or because it overflows or underflows the target type, cin
goes into an error state (cin.good()
returns false) and any further read operation is a no-op. Put calls to cin.ignore
(to clear out remaining input) and cin.clear
(to reset error flags) into the loop.
Even then, you can still run into an issue if the user enters EOF (Ctrl+D on Unix, Ctrl+Z on Windows). You need your loop to understand that part too and break out.
#include <iostream>
#include <limits>
using namespace std;
int main() {
unsigned short value;
cout << "Enter the value (0-3):" << endl;
while(true) {
cin >> value;
if (!cin || value < 0 || value > 3) {
if (cin.eof()) {
cout << "End of input, terminating." << endl;
return 0;
}
cout << "Bad input, try again (0-3):" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
cout << "The value is: " << value << endl;
}
Of course that is one hell of a lot of code just to input one number. You can practice coming up with good interfaces by trying to write a function that deals with this stuff for you.
Upvotes: 2