문제

I want to use the getch function to get a character... So the user can enter only Y OR N Character.. but the while loop is not working... I need help! Thanks

#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'

You need to use && instead of || here. Say you have entered 'Y'. So 1st test yn != 'Y' is false but 2nd test yn != 'y' is true. So the condition is true, as they are ORed. That's why it is entering the loop again.

다른 팁

You mean && not ||.

The variable "yn" is one character. For that expression to evaluate to false, that character would have to be Y, y, N, and n simultaneously, which is impossible.

You need:

while(yn != 'y' && yn != 'Y' && yn != 'n' && yn != 'N')

The logic in the while statement is flawed, you need logical AND (&&) instead of logical OR (||).

Also, this would be a good place to use do { ... } while();

The condition for the while loop is nested ORs. For it to work you might want to change them into 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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top