对于if语句,虽然它为真,但它会再次循环
For if statement, although it is true, it loops again
#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
相关文章:
- 具有嵌套 if-else 的循环的时间复杂度
- do while 循环中的 if 语句以 yes 或 no 结尾
- 如何在C++中创建 if else 循环而不是多个嵌套?
- 什么可以用来替换代码中的循环和 if 语句?
- C++ 访问 if 语句(如果它们在 for 循环中)
- 试图避免在 for 循环中出现 if-else 语句,但代码似乎有一些错误
- 如何仅在父循环的所有迭代都为真时才执行嵌套的 if 语句?
- 这个 FOR-IF 循环的解释是什么?
- 为什么这个 IF 语句在循环内不打印
- 为什么循环没有中断,并且 if 条件没有按预期工作?
- 当我的 if 语句在字符串中找到空格时,在无限循环中切换
- 我的 if 语句打印在我的 while 循环中的每个 if 语句上,无论它是否为假
- C++-循环中的If语句工作不正常
- 在C++中做一个场景问题,我不确定如何处理布尔和if循环
- While循环和if/else语句工作不正常
- C++ |如何循环 If 语句而不每次都返回值
- 如何优化循环/if语句的C
- 如何运行代码循环 if (a==b) 并且不循环如果 a != b 没有"else"
- 检测循环/if括号后的分号
- C++ 在循环"if"内丢失赋值的变量