首页 > 解决方案 > While 或 Switch 仅检测 C 中的小写而不是大写

问题描述

我想让用户写一个字母进行选择,问题是它只检测小写字母而不检测大写字母,你能帮我吗?

#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;
}

标签: cswitch-statementdo-whileuppercaselowercase

解决方案


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

'A'并且'B'被解释为“真”——表达式需要是

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

更好的选择可能是将开关移动到循环中,确保循环退出条件和开关是一致的。


推荐阅读