Search code examples
cwhile-loopalphabetical

Validation using isalpha for a loop


I am making a program in C that involves the selection of 4 options. However, I am unable to validate to check whether the value of the variable Option is a letter or number other than 1,2,3 or 4. When I enter a letter it continues to loop the print statement but not the input function and I am unable to carry on with my program. Could someone please tell me what is wrong with my code?

int Option;

while( (Option>4) || ( isalpha(Option) ) )


{

printf("Please select a valid option from the 4 options listed above! \n");

scanf(" %d",&Option);

}

Solution

  • The description for the function isalpha() states that

    In the "C" locale, isalpha returns true only for the characters for which isupper or islower is true.

    Which means that

    isalpha('4') // false
    isalpha(4) // false in ASCII-based computers
               // the ASCII table assigns 4 to a control character
    isalpha('A') // true
    isalpha(65) // true in ASCII-based computers
                // the ASCII table assigns 65 to the symbol 'A'