Is it possible to compare a number to a letter and make a difference out of it?
What I'm trying to do is:
0-10
(choose from a menu)0-10
it will
ask the user for another numberThis all works very well until the user inputs a letter (for example 'A').
I'm using scanf()
to store the value that the user inputs in an integer variable. So if the user inputs 'A'
, the value 65 gets stored in the variable.
This is causing me a lot of headache, because I want to make a difference between letters and numbers..
Here's my code for checking the input:
int checkNumber(int input,int low,int high){
int noPass=0,check=input;
if(check<low){
noPass=1;
}
if(check>high){
noPass=1;
}
if(noPass==1){
while(noPass==1){
printf("Input number between %d - %d \n",low,high);
scanf("%d",&check);
if((check>low)&&(check<high)){
noPass=0;
}
}
}
return check;
}
What happens if the user inputs a letter inside the while loop in this function; it starts looping endlessly asking for an input between low and high.
I want to somehow filter out letters, without actually filtering out the letter's values (65 and above)
.
-Is this possible?
So I continued to wrestle this problem and I came up with this solution:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
//pre: stdlib.h and ctype.h needs to be included, input cannot be initialized to a value within low and high, low cannot be greater than high
//post: returns an integer value that ranges between low and high
int checkNumber(int input,int low,int high){
int noPass=0,check=input;
if(low>high){
printf("Low is greater than high, abort! \n");
exit(EXIT_FAILURE);
}
if(isdigit(check)){
noPass=1;
}
if((check<low)||(check>high)){
noPass=1;
}
if(noPass==1){
while(noPass==1){
printf("Input a number between %d - %d \n",low,high);
scanf("%d",&check);
getchar();
if((check>=low)&&(check<=high)){
noPass=0;
}
}
}
return check;
}
int main(int argc, char *argv[]){
int i=2147483647;
printf("Choose an alternative: \n");
printf("1. Happy Fun time! \n");
printf("2. Sad, sad time! \n");
printf("3. Indifference.. \n");
printf("4. Running out of ideas. \n");
printf("5. Placeholder \n");
printf("6. Hellow World? \n");
printf("0. -Quit- \n");
scanf("%d",&i);
getchar();
i=checkNumber(i,0,6);
if(i==0){
printf("You chose 0! \n");
}
if(i==1){
printf("You chose 1! \n");
}
if(i==2){
printf("You chose 2! \n");
}
if(i==3){
printf("You chose 3! \n");
}
if(i==4){
printf("You chose 4! \n");
}
if(i==5){
printf("You chose 5! \n");
}
if(i==6){
printf("You chose 6! \n");
}
return 0;
}
It works the way I want it to, but it's not perfect. The biggest flaw is that the variable for the value in input (int i
, in main()
) cannot be initialized to a value between low and high.
For example: if int i=3; low=0 and high=6, and the user writes a letter: the value of i remains at 3. 3 is sent to checkNumber, and is immediately passed as 3.
I chose to initialize i as 2147483647, which is an unlikely number - but it is still possible.
In conclusion: it works, but it is flawed.