Reputation: 167
The default case is always executed in this switch statement, no matter what I type at the prompts.
When I type in, for example, 'A' for the second question, it prints out Invalid code entered
.
do{
printf("Please enter the quantity of dishes.\n");
scanf(" %d", &quantity);
printf("Please enter the dishes code.\n");
scanf("%d", &dishes);
switch (dishes){
case'A':case'a':sushiA(quantity);
break;
case'B':case'b':sushiB(quantity);
break;
case'C':case'c':sushiC(quantity);
break;
default:
printf("Invalid code entered.\n");
break;
}
printf("Do you still want to enter next dishes?[Y=Yes, N=No]\n");
scanf(" %c", &answer);
} while (toupper(answer) == 'Y');
Why is that?
Upvotes: 0
Views: 1249
Reputation:
do{
printf("Please enter the quantity of dishes.\n");
scanf(" %d", &quantity);
printf("Please enter the dishes code.\n");
scanf("%c", &dishes); //This line had an error
switch (dishes){
case'A':case'a':sushiA(quantity);
break;
case'B':case'b':sushiB(quantity);
break;
case'C':case'c':sushiC(quantity);
break;
default:
printf("Invalid code entered.\n");
break;
}
printf("Do you still want to enter next dishes?[Y=Yes, N=No]\n");
scanf(" %c", &answer);
} while (toupper(answer) == 'Y');
Your scanf takes dishes as integer but your switch case treats it as character .
Upvotes: 0
Reputation: 46323
If dishes
is a char
, doing scanf("%d", &dishes);
is wrong.
It scans a wrong value into the variable - a number, not a character code. It probably won't scan anything (zero?) when you type "A" because it expects a number.
Also, it's (probably) writing over unallocated memory due to different type allocating sizes (sizeof(char) != sizeof(int)
).
Use scanf("%c", &dishes)
.
Upvotes: 1
Reputation: 21917
You're scanning into dishes as an integer (%d)
, but then treating it as a character (case 'A'
). Try doing your scanf for dishes as a %c
instead
Upvotes: 1