首页 > 解决方案 > C - 如何在 ay/n 循环中排除其他输入

问题描述

所以我试图让一个简单的 y/n 输入工作。我让它工作了,当输入 n 或 N 时它会中断 while(1) 循环,但是,任何其他字母字符都会将循环设置为再次进行。我只希望它在输入 Y 时循环。

我试过: if (try_another != 'n' || try_another != 'N' || try_another != 'y' || try_another != 'Y'),在!isalpha线路之后,这没有用。

我试过scanf (" %c", try_another);然后比较分配的字符。

这是我当前的代码设置:

printf("Do you wish to try another problem [y/n]: ");

        do{
            try_another = getchar();
        /*keeps scanning for input until its a letter*/
        }while(!isalpha(try_another));
    /*when input is n or N it will end the program*/
        if (try_another == 'n' || try_another == 'N'){
            break;
        }

标签: cloopswhile-loop

解决方案


你为什么不这样做?

do {
    try_another = getchar();
} while(try_another != 'n' && try_another != 'N' && try_another != 'y' && try_another != 'Y');

你想在角色不是这个那个的时候循环。你很亲密,但不小心写了“或”而不是“和”。


推荐阅读