Do you or do you not want the user to enter an alphabet?
Do you want the letter to be converted to its ASCII value or some other value or tell the user that he shouldn't enter a letter
zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
Before using atoi() you can check each of the values in input is a letter
for example you can create a string containing alphabets as a reference like this:
char ref[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$"; // contains a to z and their corresponding capital letters as well as other unwanted input like other symbols
then you can compare this to your input string to know if it contains a letter
int i,j;
for(i = 0;i<strlen(ref);i++){
for(j = 0;j<strlen(input);j++){
if(input[j] == ref[i]){
printf("Invalid Input");
break;
}
}
}
Then put these in a loop that has a boolean like use, as long as the user input has a letter the program will not continue
P.S. strlen() is from the string.h library you can use numbers to reference the length of the string as a condition for the for loop if you like
zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
Oh so you want to end the program if the input is invalid
You could make the rest of the code run only if a condition is met
ex.
int main(void){
int i,j, dontrun = 1;
for(i = 0;i<strlen(ref);i++){
for(j = 0;j<strlen(input);j++){
if(input[j] == ref[i]){
printf("Invalid Input");
dontrun = 0;
break;
}
}
}
if(dontrun == 1){
//rest of the codes are here
}
}
zeroliken
Veteran Poster
1,106 posts since Nov 2011
Reputation Points: 201
Solved Threads: 162
atoi() has no way to recover from errors. Use strtol() as subith86 suggested.
Should you actually want to test whether a character is a digit, don't perform contortions; #include and use isdigit instead.
Trentacle
Junior Poster in Training
72 posts since Dec 2010
Reputation Points: 110
Solved Threads: 20
Nowhere do you properly test for valid input.
In the loop
for(j = 0; j <= strlen(input); j++)
{
if(input[j] == ref[i])
{
run = 1;
}
else if(input[j] != ref[i])
{
run = 0;
}
}
you give it a try, but if the last character tested is good, you set the entire input to good. Follow that code with pencil and paper.
In the line status = scanf("%s", input); you
1) return a status but never test it where it does any good.
2) read only up to the first whitespace, so an input of "2 A +" only reads "2".
3) Read this .
Here's the secret to solving most of your errors immediately: printf() !!!
Print values to see what they are at key spots in your code. Displayinginput immediately after your scanf() would have shown you what your major problem is.
Also,[url=http://www.gidnetwork.com/b-38.html]proper formatting will help a lot in readability. Concentrate on better indentation.
WaltP
Posting Sage w/ dash of thyme
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944