Click to See Complete Forum and Search --> : Function for not accepting letters?
Bazoukas90
07-02-2001, 01:06 PM
Ok here is my question. I wrote a very simple program and I was wondering if there is a function that will not accept a letter as a value.
here is the code.
#include <iostream.h>
int main() {
int x;
cout << " Please enter a number : " ;
cin >> x;
if (x>10)
cout << x << " is larger than 10.";
else if(x<10)
cout << x << " is smaller than 10:";
else if(x==0)
cout <<x << " Is equal to 10";
else
cout << " You have entered an invalid character.";
return 0;
}
Now when I enter a letter or a character it translates it to a number and compares it to 10. Anybody knows if there is a function that wont allow this to happen?
thank you mucho.
Grizzly
07-02-2001, 01:39 PM
What's happening is your program is translating the letters into their "ordinal" values, as defined in the ASCI character set.
There's probably a better way to do this...
but you could append this into your if statement:
elseif( (x >= 'A') | | ( x <= 'z' ) ){
cout << " You have entered an invalid character.";
}
Read here for more on ordinal values in the ASCII set. http://www.cs.nyu.edu/courses/spring99/A22.0002.002/lecture_notes/lecture5/node16.html
Grizzly
07-02-2001, 01:40 PM
Oops, bad connection at the time http://www.sharkyforums.com/ubb/smile.gif
[This message has been edited by Grizzly (edited July 02, 2001).]
elseif( (x >= 'A') | | ( x <= 'z' ) ){cout << " You have entered an invalid character.";}
I don't think this will work, as he may WANT to use the numerical values from 65 to 122. He'd have to do something like what was discussed in an earlier thread, which was using a buffer.
You'll probably want to use an array of 12 characters (10 for digits, 1 for a sign, and 1 for the null character). You'll have to loop through the array checking each character against some conditions until you hit the null. Then you'll need to convert the string into an integer, which is pretty easy.
Ex:
bool valid_int(char *someString)
{
char *c = someString;
count = 0;
if (*c == 0)
return false;
if ((*c == '-') | | (*c == '+'))
c++;
while ((*c != 0) && (count < 10))
{
if ((*c < 48) | | (*c > 57))
{
return false;
}
c++;
count++;
}
if (count > 10)
return false;
return true;
}
Two problems with this that I don't feel like testing to fix:
1. This doesn't check to see if the number is greater than 2^32
2. I'm not sure if count is being checked correctly (count is used to find out the number of digits we got).
Close enough http://www.sharkyforums.com/ubb/smile.gif
int str_to_int(char *someString)
{
int x = 0;
int scale;
int count = 0;
char *c = someString;
if (*c == '-')
{
scale = -1;
c++;
}
else if (*c == '+')
{
scale = 1;
c++;
}
else
{
scale = 1;
}
while (*c != 0)
{
x += power(10, count) * (*c - 48);
count++;
c++;
}
return scale*x;
}
I think that works http://www.sharkyforums.com/ubb/smile.gif
[This message has been edited by Zoma (edited July 02, 2001).]