检查是否输入了两个字符之一的循环永远运行

Loop to check whether one of two characters was entered runs forever

我正在尝试编写一个代码,在我按下右键(m 或 o)后将打印 "Yayy",但我在运行时卡住了……我可以按任何键,它仍然会询问我要按一下..

#include <stdio.h>
int main() {
    char input_char;
    printf("Press a key:");
    input_char = getc(stdin);
    printf("You pressed:%c\n", input_char);

    while (input_char != 'm' || input_char != 'o') {
        printf("Press a key:");
        input_char = getc(stdin);
        input_char = getc(stdin);
        printf("You pressed:%c\n", input_char);
    }
    printf("Yayyy");
}

想想这个检查:

while (input_char != 'm' || input_char != 'o') {

这表示 "loop while input_char isn't m or input_char isn't o." 但如果你仔细想想, 每个 字符要么不是 m,要么不是 o。 (你知道为什么吗?)结果,这将永远循环。

要解决此问题,请将循环更改为读取

while (input_char != 'm' && input_char != 'o') {

表示 "loop as long as the input isn't m and the input isn't o." 这样,如果输入是 m 或输入是 o,循环将停止 运行。 (你明白为什么了吗?)

另一个小修复 - 没有理由在循环内调用 getc 两次。那是两个字符,但你只会记住其中一个。

希望对您有所帮助!

您希望用户按 m 或 o,因此循环应该 运行 而输入不是 m 也不是 o。您需要更改此行:

while (input_char != 'm' || input_char != 'o')

为此:

while (input_char != 'm' && input_char != 'o')