#include <stdio.h>
#include <iostream>
using namespace std;
float cost, total;
bool loop(char item){
switch (toupper(item)) {
case 'A':
cost = 4.25;
return true;
case 'B':
cost = 5.57;
return true;
case 'C':
cost = 5.25;
return true;
case 'D':
cost = 3.75;
return true;
case 'T':
return false;
}
return true;
}
int main(){
char item;
do {
printf("\nEnter Item Ordered [A/B/C/D] or T to calculate total:");
scanf("%c", &item);
total = total + cost;
} while (loop(item));
printf("Total Cost: $%f\n", total);
}
Let me output the process:
$ ./Case3.o
Enter Item Ordered [A/B/C/D] or T to calculate total:a
Enter Item Ordered [A/B/C/D] or T to calculate total:
Enter Item Ordered [A/B/C/D] or T to calculate total:b
Enter Item Ordered [A/B/C/D] or T to calculate total:
Enter Item Ordered [A/B/C/D] or T to calculate total:a
Enter Item Ordered [A/B/C/D] or T to calculate total:
Enter Item Ordered [A/B/C/D] or T to calculate total:t
Total Cost: $28.139999
Why is it after the first printf its printing the printf twice but skipping me from input the first time. then how is it calculating 5.24+5.57+5.24 to equal 28.14?
As others have mentioned, When you press Enter, two characters get inputted,
the character you enter + the newline, You need to account for both of these.Possible solutions are:
Approach 1: The C way
Add a space here, or the better approach,
Approach 2: The C++ way
simply use the C++ way of getting input from user.
Why the result is Undefined?
Because you did not initialize the variabletotal, This results in Undefined Behavior giving you unexpected output.totalis a global so it will be Default Initialized to 0.0.Real reason for Undefined result is in @Mystical’s answer.