int ch
do
{
cout<<"\n ENter your choice";
cout<<"\n 1 2 3";
cin>> ch;
switch(ch)
{
case 1: cout<<"One";
break;
case 2: cout<<"two";
break;
case 3:exit (0);
default:cout<<"Not a valid choice";
break;
}
}whiel(!(ch==3));
in the above code whenever i enterd alphabet program goes infinite. i have also tried isdigit() function but can't run correctly...
any one help me?
I tried to give you a solution, but that didn't work..
Here's how it is. cin (or any stream) object contains an error flag. Amongst other situations this flag is set when you want to read a number, but there aren't any in the stream. When the flag is set, all IO operations are made unavailable until the error is handled. Handling such error would mean two things. Clear the error flag and remove the offending characters from the stream. You check the flag using fail() method (note that there are more). An interesting thing is that if(cin) is the same as if(!cin.fail()). I will not discuss how that works here.. To clear the flag, use method clear(). Removing garbage is not as nice. You could write cin.ignore(numeric_limits<streamsize>::max(), '\n'); where numeric_limits<streamsize>::max() needs <limits> included and is just a big number (you'd be fine if you used 100 instead). You could also read a dummy string with getline, although that's wasteful, unless you want to tell the user exactly what the problem was.