对于if语句,虽然它为真,但它会再次循环

For if statement, although it is true, it loops again

本文关键字:循环 if 对于 语句      更新时间:2023-10-16
#include <stdio.h>
void clearKeyboard(void){
    while(getchar()!='n');
}
void pause(void){
    printf("Press <ENTER> to continue...");
    clearKeyboard();
}

int getMenuChoice(void){
    int choice;
    printf("1- List all itemsn");
    printf("2- Search by SKUn");
    printf("0- Exit programn> ");
    scanf("%d", &choice);
    return choice;
}
int getYesOrNo(void){
    char ch;
    int ret;
    ch = 0;
    ret = 0;
    while(ch != 'Y' || ch != 'y' || ch != 'N' || ch != 'n')
    {
            scanf("%c", &ch);
            clearKeyboard();
            if (ch == 'Y' || ch == 'y'){
                    ret = 1;
                    return ret;
            }
            if (ch == 'N' || ch == 'n'){
                    ret = 0;
                    return ret;
            }
            else if (ch != 'Y' || ch != 'y' || ch != 'N' || ch != 'n'){
                    printf("Only (Y)es or (N)o are acceptable: ");
            }
    }
    return ret;
}
int main(void){
    int choice;
    int temp = 0;
    choice = 0;
    printf("=== TEST MENU ===n");
    pause();
    while(temp == 0){
            choice = getMenuChoice();
            if (choice != 0){
                    printf("*** not implemented ***n");
            }
            else{
                    printf("Do you really want to quit? ");
                    temp = getYesOrNo();
            }
    }
    printf("=== END OF MENU TEST ===n");
    return 0;
}
当代码运行时,它应该打印出测试菜单我必须按回车键继续 然后,它将显示多个print语句(listall..)搜索…退出)

如果用户输入0,它会问你是否真的想退出如果用户输入y,它应该退出

然而,问题是程序在问"你真的想退出吗?"之后再次问用户不必要的问题"只有(Y)个或(N)个是可接受的",而我已经输入了Y,这是有效的答案。

为什么?

p。S库是否存在

Scanf ("%d", &choice);只消耗数字字符(在任何其他输入上也会崩溃,iirc),但不消耗r l或n字符,如果我是正确的(请有人纠正我),这些字符将在getYesOrNo函数期间消耗。这就是为什么程序应该在询问你是否真的想退出后直接显示(y)es/(n)o提醒。

这也是添加clearKeyboard函数使其按预期工作的原因。

该代码还有一些其他问题(例如评论中提到的UB)。然而,这

        if (ch == 'Y' || ch == 'y'){
                ret = 1;
                return ret;
        }
        if (ch == 'N' || ch == 'n'){
                ret = 0;
                return ret;
        }
        else if (ch != 'Y' || ch != 'y' || ch != 'N' || ch != 'n'){
                printf("Only (Y)es or (N)o are acceptable: ");
        }

可能不是你想要的。第一个if独立于后面的if - else,因此即使第一个条件为真,之后的块也会被求值。最有可能的情况是:

        if (ch == 'Y' || ch == 'y'){
                ret = 1;
                return ret;
        }
        else if (ch == 'N' || ch == 'n'){
                ret = 0;
                return ret;
        }
        else {
                printf("Only (Y)es or (N)o are acceptable: ");
        }

条件ch != 'Y' || ch != 'y' || ch != 'N' || ch != 'n'不是真正有意义的,因为字符总是要么不是Y要么不是N,因此它总是为真。

您应该在%c之前添加一个空格,以自动跳过任何前导空格。在您的情况下,'n'总是存储在ch中,这就是为什么else if (ch != 'Y' || ch != 'y' || ch != 'N' || ch != 'n')总是为真


scanf(" %c", &ch); //This is the modified statement