Make this program only respond.....
How would I make this program only respond "yes, x is 12" to only inputted -numbers- not letters.
#include <iostream>
using namespace std;
int main()
{
int x = 12;
cin >> x;
if(x == 12)
{
cout << "yes, x is 12." << endl;
system("pause");
return 0;
}
else
{
cout << "No!" << endl;
system("pause");
return 0;
}}
[422 byte] By [
akk] at [2007-11-11 7:40:04]

# 1 Re: Make this program only respond.....
I think this is what you want..
You can use the isdigit() method. it accepts a int, and returns a bool. It checks the ascii value, NOT the actual number. the following code will demonstrate how to read in a character and tell if it is a number or not.
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
char c;
cin >> c;
int x = (int) c;
if (isdigit(x)) {
cout << "You enetered a digit." << endl;
} else {
cout << "You did not enter a digit." << endl;
}
return 0;
}
destin at 2007-11-11 21:02:00 >

# 2 Re: Make this program only respond.....
isdigit will not work here because it shoud be used for char variables, not integers.
I think the program in its original form does what it should do: it prints the right message when the user enters the sequence "12". Any other value entered causes the else clause to execute so there's no need to change the program.
Danny at 2007-11-11 21:03:01 >

# 3 Re: Make this program only respond.....
isdigit will not work here because it shoud be used for char variables, not integers.
I said that in my post.
destin at 2007-11-11 21:04:00 >

# 4 Re: Make this program only respond.....
I said that in my post.
Yes, now I see it;)
However, your code won't work either because you can't read two digits into one char. When the user enters 12, only the first char will be stored in c as '1'. So the program has to read either an int, and then compare it to 12, or a string and then convert to a number, before any other tests are applied.
Danny at 2007-11-11 21:05:06 >
