4

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();
}
newbie
  • 14,582
  • 31
  • 104
  • 146
  • 1
    It would be helpful to explain how it is not working, or any efforts you have made to solve this problem. – wj32 Dec 02 '10 at 11:26
  • 1
    the expression `x != A || x != B` will be always true. `x` has only one value :) – ruslik Dec 02 '10 at 11:30

5 Answers5

5
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.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
1

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')
AlastairG
  • 4,119
  • 5
  • 26
  • 41
1

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();

Neno Ganchev
  • 746
  • 8
  • 14
1

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');
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
1
//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
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574