题
我想使用getch函数来获得角色...因此用户只能输入y或n角色。但是while循环不起作用...我需要帮助!谢谢
#include <stdio.h>
main(){
char yn = 0;
printf("\n\t\t Save changes? Y or N [ ]\b\b");
yn = getch();
while (yn != 'Y' || yn != 'y' || yn != 'N' || yn != 'n') { //loop is not working
yn = getch();
}
if (yn=='Y' || yn=='y') printf("Yehey");
else printf("Exiting!");
getch();
}
解决方案
yn != 'Y' || yn != 'y' || yn != 'N' || yn != 'n'
您需要使用&&而不是||这里。假设您已经进入“ Y”。因此,第1个测试yn!='y'是错误的,但是第二个测试yn!='y'是正确的。因此,这种情况是真实的。这就是为什么它再次进入循环的原因。
其他提示
您的意思是&&不是||。
变量“ yn”是一个字符。为了使该表达评估为错误,该角色必须同时为y,y,n和n,这是不可能的。
你需要:
while(yn != 'y' && yn != 'Y' && yn != 'n' && yn != 'N')
While语句中的逻辑是有缺陷的,您需要逻辑和(&&)而不是逻辑或(||)。
另外,这将是使用{...} while()的好地方;
条件 while
循环是嵌套的。为了使其工作,您可能想将它们更改为Ands:
do {
yn = getch()
} while(yn != 'Y' && yn != 'y' && yn != 'N' && yn != 'n');
//use of getch() function
#include<iostream.h>
#include<conio.h>
//main function starts excuition
viod main()
{
clrscr();//to clear the screen
//veriable decleration
int a;//Any integer
int b;//Any integer
int c;//Any integer
cout<<"Enter the first number\n";//prompt
cin>>a;//read the integer
cout<<"Enter the second number\n";//prompt
cin>>b;//read integer
c = a + b;//the value of xum of "a" and "b" is assigned to "c"
cout<<"sum is\t"<<c;
getch();//to stay the screen
}
不隶属于 StackOverflow