-
Hello everybody,
I am new to C++ and need some help.
In my little program, I declared a variable as integer
and use cin to capture the input from user. How can I validate the datatype to make sure the input is really an integer and not an alphabet?
BTW, the declaration of the variable as an integer does not prevent the user from typing in an alphabet. I tested that.
//my codes:
#include <isostream.h>
int main()
{
int num;
cout << "Please input a number: ";
cin >> num;
if //num is an integer <-- this is where I need help
//then do something
else
cout << "Invalid input" << endl;
}
//end of codes
FYI, I am using VC++ 6.0 and the program is a simple Win32-console application.
Thank you very much.
nina.
-
You need to #include <ctype.h>, then use the isdigit function.
-
Thank you for the response, parksie! I tried that but it is still not working. It keeps going to my outermost "else" statement when I type in anything. And if I change the validation statement to if(!isdigit(intGrade)), it acts like the statement never exist.
I attached my codes below. Will you please look at it and see if I have done it correctly or not? Thank you very much.
//My codes
#include <iostream.h>
#include <ctype.h>
int main()
{
int intGrade;
cout << "Please input your score: ";
cin >> intGrade;
if (isdigit(intGrade))
if (intGrade >= 0 && intGrade <= 100)
{
if (intGrade >= 90 && intGrade <= 100)
cout << "Your grade = A" << endl;
else
if (intGrade >= 80 && intGrade <= 89)
cout << "Your grade = B" << endl;
else
if (intGrade >= 70 && intGrade <= 79)
cout << "Your grade = C" << endl;
else
if (intGrade >= 60 && intGrade <= 69)
cout << "Your grade = D" << endl;
else
cout << "Your grade = F" << endl;
}
else
cout << "Invalid input: You must input a number from 0 to 100." << endl;
else
cout << "Invalid input: Please enter an integer only." << endl;
return 0;
}
//end of codes
-
Ah -- I see now. What's happening is you type in a number, say 99. This is converted to an integer, but isdigit takes a SINGLE digit, and checks it, so what it's doing is comparing the character code 99. :(
The problem with all the conversion functions is that they return 0 if no conversion could be performed...you could either code up something vicious to protect it, or just accept that anything bad will appear as 0.
I should be able to get something going if you really need it.
-
parksie,
I will appreciate that if you don't mind to spend the time. I believe by going that extra steps to make a better program will help me better understand the language.
Again, thank you very much.
nina.