Search code examples
cgetch

Help with getch() function


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

Solution

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