'Basic problem of while loop in c with or operator, using to get choice from user
So the problem is very simple but I mess it up somehow. I create a menu with this code:
#include<stdio.h>
int main(){
int n;
int choice;
printf("\nMENU:\n");
printf("\n1- Add new student");
printf("\n2- Print student List");
printf("\n3- Find max average grade");
printf("\n4- Find a student by name");
printf("\n5- Delete student by ID");
printf("\n6- Export data file");
printf("\n0- Quit\n");
printf("\nPlease enter your choice: ");
scanf("%d", &choice);
fflush(stdin);
while(choice!=1 || choice!=2 || choice!=3 || choice!=4 || choice!=5 || choice!=6 || choice!=0){
printf("Please enter again: ");
scanf("%d", &choice);
fflush(stdin);
}
}
The while loop force user to only enter 1 to 6 or 0 to quit. However the loop will also execute when I enter those value. What have I messed up?
I know this is a basic concept in c and I have already using it many times but this is the first time I saw this.
Solution 1:[1]
Make an habit of reading C expressions out aloud/in your head, then apply common sense afterwards.
"if choice isn't 1 or it isn't 2..." Wait, that doesn't make sense.
"if choise isn't 1 AND it isn't 2..." That makes sense.
Also related and generally helpful for programmers: De Morgan's Laws
Unrelated to your question, the source of learning that told you to use fflush(stdin) is bad and needs to be retired and replaced. See Using fflush(stdin)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lundin |
