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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With