如何使我的 switch 语句正确循环?

How do I make my switch statment loop properly?

当输入字符 A B 或 C 时,它 returns 它们的数值。

如果是第一次输入任何内容,则打印默认语句。 THEN 如果您输入 A B 或 C,它会正确打印,但之后无论如何都会打印 Default 语句。

/*#define_USE_C99_MATH*/
/*#include <stbool.h>*/
#include <stdio.h>

main ()
{
    int ABC;     /* I/O */
    char c1 = 'A'; /*Characters to be entered*/
    char c2 = 'B';
    char c3 = 'C';

    /*typedef enum { false, true } bool;*/
    printf("Please enter either A, B, or C (case sensitive):");
    ABC = getchar();
    /*bool loop = true;*/

    if ((ABC = getchar()) == c1 | c2 | c3)
    {
        do
        {
            switch (ABC)
            {
            case 'A':    
                printf("The numerical value of A is: %d\n", c1);
                break;

            case 'B':    
                printf("The numerical value of B is: %d\n", c2);
                break;  

            case 'C':    
                printf("The numerical value of C is: %d\n", c3);
                break;  

            default:
                printf("The character you have entered is not valid.\n");
                break;
            }
        } while ((ABC = getchar()) != c1 | c2 | c3);
    }
    else
    {
    }

    return 0;
}

您的错误似乎是您输入了 if 语句,该语句只有在您输入 'A' 'B' 或 'C' 时才会起作用。不过在我看来,我认为最好不要在此程序中使用 if 语句。相反,只要保留 do while 循环,代码就会 运行 正常。

您应该使用逻辑或 || 而不是按位或 |在这种情况下您仍然可以使用 | 但它有助于代码更具可读性)。你可能会遇到使用输入函数的问题,因为当用户通过 getchar() 输入输入时,它实际上发送了 2 个字符,比如 A\n 所以你需要再次使用换行符getchar()

我已经在此处修改了您的代码,但它的行为仍然相同:

#include <stdio.h>

main ()
{
    char ABC;
    char c1 = 'A';
    char c2 = 'B';
    char c3 = 'C';

    printf("Please enter either A, B, or C (case sensitive):");
    ABC = getchar();

    while(ABC != c1 && ABC != c2 && ABC != c3)
    {
        getchar(); // Consume \n
        printf("The character you have entered is not valid.\n");
        ABC = getchar();
    }

    switch (ABC)
    {
    case 'A':    
        printf("The numerical value of A is: %d\n", c1);
        break;

    case 'B':    
        printf("The numerical value of B is: %d\n", c2);
        break;  

    case 'C':    
        printf("The numerical value of C is: %d\n", c3);
        break;  
    }

    return 0;
}

为什么不删除 if 语句,因为如果你这样做,你将有机会让你的默认情况为真,另一个你可能出错的原因是:

while ((ABC = getchar()) != c1 | c2 | c3);

变成:

while ((ABC = getchar()) != c1 | ABC != c2 | ABC != c3);