I’m trying to nest a if/else inside a case switch statement. When I enter case ‘p’ or ‘P’ no matter what character is typed the $15.00 line is printed. I have tried moving/adding {}’s with no change in output.
Thanks for taking time to help a noob out.
Entire code now here.
#include <stdio.h>
int main()
{
//variable declarations
char typeOfWash, tireShine;
//Menu
printf("R ---> Regular ($5.00)\n");
printf("B ---> Bronze ($7.50)\n");
printf("G ---> Gold ($10.25)\n");
printf("P ---> Platinum ($15.00)\n");
printf("Tire Shine can be added to the Gold or Platinum ONLY,");
printf("for an additional$2.50\n\n");
printf("Enter your selection: ");
scanf("%c",&typeOfWash);
switch (typeOfWash)
{
case 'R': case 'r':
printf("Your bill total is: $5.00\n");
break;
case 'B': case 'b':
printf("Your bill total is: $7.50\n");
break;
case 'G': case 'g':
printf("Would you Like a Tire Shine? (Y/N): ");
scanf("%c ",&tireShine);
if (tireShine == 'Y' || tireShine == 'y')
printf("Your bill total is: $12.75\n");
else
printf("Your bill total is: $10.25\n");
break;
case 'P': case 'p':
printf("Would you Like a Tire Shine? (Y/N): ");
scanf("%c ",&tireShine);
printf("%c",tireShine);
if (tireShine == 'Y' || tireShine == 'y')
printf("Your bill total is: $17.50\n");
else
printf("Your bill total is: $15.00\n");
break;
default:
printf("Invalid Choice");
}
return 0;
}
The problem is that using
scanfwith the%cformat specifier results in white space not being consumed, which in your case results in a\nbeing left in the input buffer. What your instructor seems to have suggested is to eat the trailing white space from the initial input with the nextscanf; however, I suspect that they said to insert a leading space rather than a trailing space as this fixes your problem:Alternatively, you could use
getchar()immidiately before your secondscanfand consume the new line character beforehand:A second alternative would be to use the
%sformat specifier instead of%cand handle it accordingly.Be warned that
getchar()will only consume one character from the input buffer. If a user were to input a string longer than 1 character, for example, you would need to have something likewhile ((x = getchar()) != '\n') ;to clear the buffer.