How to check if a string is a letter(a-z or A-Z) in c
21,736
Solution 1
You can use the isalpha()
and isdigit()
standard functions. Just include <ctype.h>
.
if (isdigit(integer)) != 0){
printf("Got an integer\n");
}
else if (isalpha(integer))
printf"Got a char\n");
}
else{
// must be an operator
}
Solution 2
To find out if the input is a letter or a digit:
-
int isalpha ( int c );
function to verify whetherc
is an alphabetic letter. -
int isalnum ( int c );
function to verify whetherc
is either a decimal digit or an uppercase or lowercase letter. -
int isdigit ( int c );
function to verify whetherc
is a decimal digit character.
To find out if the letter is uppercase or lowercase:
-
int islower ( int c );
to checks whetherc
is a lowercase letter: a-z -
int isupper ( int c );
to checks whetherc
is a uppercase letter: A-Z
Put them into if
statements which do something (true
or false
), depending on the result.
PS You can find out more about standard library here: Character handling functions: ctype.h
Author by
Talen Kylon
Updated on July 09, 2022Comments
-
Talen Kylon almost 2 years
I am getting user input, and I want to determine if the user has entered a letter , an integer, or an operator. I can successfully determine if it is an integer using sscanf, but I am stumped on how to determine if it is a letter.
By letter, I mean: A-Z, a-z.
int main(){ char buffer[20]; int integer; printf("Enter expression: "); while (fgets(buffer, sizeof(buffer), stdin) != NULL){ char *p = strchr(buffer, '\n'); //take care of the new line from fgets if (p) *p = 0; //Buffer will either be a integer, an operator, or a variable (letter). //I would like a way to check if it is a letter //I am aware of isalpha() but that requires a char and buffer is a string //Here is how I am checking if it is an integer if (sscanf(buffer, "%d", &integer) != 0){ printf("Got an integer\n"); } else if (check if letter) // need help figuring this out } else{ // must be an operator } } }
-
chux - Reinstate Monica over 10 yearsBTW: If you entered only spaces,
(sscanf(" ", "%d", &integer)
would yield -1 and pass your "Got an integer\n" test. Recommend in the future use affirmativesscanf()
comparison tests such assscanf(buffer, "%d", &integer) == 1
forsscanf(..., "%d",...)
may be expected to return 0, 1 or EOF.
-
-
Talen Kylon over 10 yearsThanks for the suggestion, but how do change buffer to an integer?
-
Giuseppe Pes over 10 yearsjust use the first character of the buffer and cast it to
int
.