Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with getch() function

Tags:

c

getch

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();
}
like image 534
newbie Avatar asked Jan 20 '23 23:01

newbie


2 Answers

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.

like image 134
taskinoor Avatar answered Jan 30 '23 00:01

taskinoor


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')
like image 24
AlastairG Avatar answered Jan 29 '23 23:01

AlastairG