0

How to use while with two situations?

I use while(ch!=3 || ch!=17) to run the program, but when I press "ctrl+q" or "ctrl+c", it dosen't stop. How to correct it? Thank you. ------ #include <stdio.h> #include <stdlib.h> int main(void) { char ch; while(ch!=3 || ch!=17) { ch=getche(); printf("\nASCII of ch=%d\n",ch); } system("pause"); return 0; }

11th Jan 2019, 5:05 AM
Eason Huang
Eason Huang - avatar
5 Respostas
+ 4
Your original while should be: while (ch!=3 && ch!=17) If ch is 48 or '0', it is not equal to both. When it is cntrl-c, it is 3. But, it is not 17 so the loop keeps going. The only way to stop that loop was for ch to be both 3 and 17.
11th Jan 2019, 9:53 AM
John Wells
John Wells - avatar
+ 2
See John Wells knew more about the codes than I did. Plus I missed that fatal piece of logic where an OR in a while loop for key pressing is not ok. It was late (excuses), but I'm glad you got some actual help
11th Jan 2019, 2:07 PM
Zeke Williams
Zeke Williams - avatar
+ 1
John Wells Zeke Williams Thank you very much !!
11th Jan 2019, 3:02 PM
Eason Huang
Eason Huang - avatar
0
I don't know the getche function that well, but I thought it only waits for ONE single character. 17 is two. Are you trying to check for the character code? If so, you'll have to convert ch to an integer. Otherwise, you need to put single quotes around 3. 17 won't work as a character: != '3'
11th Jan 2019, 5:13 AM
Zeke Williams
Zeke Williams - avatar
0
Zeke Williams Thank you for your help! But I thought it is not the problem about numbers of character. When I used while(ch!=17) or while(ch!=3) individually, it works. I want to know why put them together with "||" doesn't work in while function. Btw, I modified the program(below) successfully and it works. ------ #include <stdio.h> #include <stdlib.h> int main(void) { char ch; int a; while(a!=1) { ch=getche(); printf("\nASCII of ch=%d\n",ch); if (ch==3 || ch==17) a=1; } system("pause"); return 0; }
11th Jan 2019, 6:18 AM
Eason Huang
Eason Huang - avatar