Search code examples
cswitch-statementdo-whileuppercaselowercase

While or Switch only detect lower-case and not upper-case in C


I would like the user to write a letter for a selection, the problem is that it only detects lowercase letters and not uppercase, could you help me?

#include <stdio.h>
#include <ctype.h>

int main ()
{
    char choice;
    
    printf("Will you choose A, or B?\n>");
    
    do {
        scanf(" %c", &choice);
    } while (choice != 'a' && 'A' && choice != 'b' && 'B');

    switch (choice) {
        case 'A':
        case 'a':
            printf("The First Letter of the Alphabet\n");
            break;
        case 'B':
        case 'b':
            printf("The Second Letter of the Alphabet\n");
            break;
    }

    system("pause");
    return 0;
}

Solution

  • In

    choice != 'a' && 'A' && choice != 'b' && 'B'
    

    'A' and 'B' are just interpreted as "true" -- the expression needs to be

    choice != 'a' && choice != 'A' && choice != 'b' && choice != 'B'
    

    A better alternative might be to move the switch into the loop, making sure the loop exit condition and the switch are consistent.