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");开发者_如何学C
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')
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();
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');
//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
}
精彩评论