-
avoid char input, help!
supose
i have to input a series of integer and count for odd and even number.
However, would not allow to input character if mistake. In order to do that,
the program should return to begin, but not to exit.
I use
cout<<"Enter an integer: ";
cin>>integ;
if (!cin)
{cout<<"Enter again";
cin>>integ;
}
but the program still exit.
anyone can help?
-
I haven't tested this function extensively, but I think it should work.
Code:
template<typename T> bool myget(T& t)
{
using std::cin;
using std::ios;
cin>>t;
if (cin.eof())
cin.clear();
else if (cin.fail())
{
cin.clear();
cin.ignore(10000,'\n');
}
else if (cin.bad())
cin.clear();
else
{
cin.ignore(10000,'\n');
return true;
}
return false;
}
Use it like this is main()
Code:
int main()
{
int integ;
do
{
cout <<"Enter an integer: ";
} while(!myget(integ));
//...
}