i ma trying to check that my input is always an int.
if it w'll be a char it will genertae an error
The problem is chars are stored as ints. A char 'Z' is the same as int 90 if you are using ASCII. If you want to see if your input is not a char you would need to see if there is a standard i/o that will allow you to check or you can do something like
if (input > 'A' && input <= 'z')
then you know you have a char
int main()
{
int test;
bool rval;
while (1) //infinite loop. Need CTRL+C to stop program
{
rval = GetInt(test);
if (rval)
{
cout << "The integer is: " << test << endl;
}
else
{
cout << "Error! Eating an input character" << endl;
//You could use cin.get() here to see what you ate
cin.ignore();
}
}
return 0;
}
bool GetInt(int& data)
{
cin >> data;
if (cin.good())
{
return true;
}
else
{
cin.clear(); //clear the fail bit that got us here
return false;
}
}
[/code]
Here the cin >> data (an int) is followed by a test of the goodbit. In the case of the A, the goodbit is false. The istream is now in a fail state and the A is still in the input buffer. In this case you clear() the fail state. The A is still in the buffer.
int main()
{
int test;
bool rval;
while (1) //infinite loop. Need CTRL+C to stop program
{
rval = GetInt(test);
if (rval)
{
cout << "The integer is: " << test << endl;
}
else
{
cout << "Error! Eating an input character" << endl;
//You could use cin.get() here to see what you ate
cin.ignore();
}
}
return 0;
}
bool GetInt(int& data)
{
cin >> data;
if (cin.good())
{
return true;
}
else
{
cin.clear(); //clear the fail bit that got us here
return false;
}
}
[/code]
Here the cin >> data (an int) is followed by a test of the goodbit. In the case of the A, the goodbit is false. The istream is now in a fail state and the A is still in the input buffer. In this case you clear() the fail state. The A is still in the buffer.
So you have to eat the A and try again.
duh, I forgot cin does more then just read bits from the input stream. Its been so long since I did console apps like that. Guess its time to review the basics.
Comment