The problem of your code is not related to the alphabetical character check: in fact you are actually checking just the first character of the string, as you break the loop in both the if
and else
branches.
I suppose you just want to interrupt the elaboration just when an invalid character is found:
#include <ctype.h>
#include <string.h>
char word[20];
printf("Enter a word: ");
fgets(word, 19, stdin);
word[strcspnn(word, "\n")] = 0;
for(int i=0;i<strlen(word);i++){
if((isalpha(word[i]))){
printf("Alphabet");
// break; // No break required here!
}else{
printf("Illegal input");
break;
}
}
Please note how:
- I used
fgets
instead of gets
: the latter is deprecated because it is unsafe. On the other hand, fgets
is able to control the number of characters acquired, without the risk to go beyond the size of the word
array
- Since
fgets
stores also the trailing newline, I search for it and substitute with the string terminator (as wonderfully shown [here])(https://stackoverflow.com/a/28462221/11336762)
- Using all those magic numbers to check the range from the characters is bad practice. You can do the same by using standard function
isaplha()
, contained within ctype.h