Help with getch () function

I want to use the getch function to get the character ... Thus, the user can only enter 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(); } 
+4
source share
5 answers
  yn! = 'Y' ||  yn! = 'y' ||  yn! = 'N' ||  yn! = 'n' 

You need to use && instead of || Here. Say you entered "Y". So, the 1st test yn! = 'Y' is false, but the 2nd test yn! = 'Y' is true. So, the condition is true, since they are ORed. That is why it is entering the cycle again.

+5
source

You mean && not ||.

The variable "yn" is one character. In order for this expression to be evaluated as false, this character must be Y, y, N, and n at the same time, which is impossible.

You need:

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

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

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

+1
source

The condition for the while is a nested OR. For it to work, you can change them to AND:

 do { yn = getch() } while(yn != 'Y' && yn != 'y' && yn != 'N' && yn != 'n'); 
+1
source
 //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 } 
+1
source

All Articles