1
char word[20];
printf("Enter a word: ");
gets(word);
for(int i=0;i<strlen(word);i++){
    if((word[i]>=97 && word[i]<=122) || (word[i]>=65 && word[i]<=90)){
        printf("Alphabet");
        break;
    }else{
        printf("Illegal input");
        break;
    }
}

Why is this wrong? I need only one word from the user. If there are any spaces or nonalphabetic characters, it must print illegal input. How do I correct this?

1 Answers1

1

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
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39