I am fully aware that switch must be used with int but my assignment is requiring me to use switch in regards to user input which will be strings. I've looked and I've seen some mentioning stoi but I'm not sure if that is what my professor is expecting b/c we have not been introduced to it yet. I'm completely new to C so I'm still learning and this code is not completed yet but can anyone please help me with this?
int main()
{
// Declare Constant variables
const float DISC_GOLF_RETAIL = 14.96;
const float ULTIMATE_RETAIL = 20.96;
const double DISCOUNT1 = 8;
const float DISCOUNT2 = .16;
const float DISCOUNT3 = .24;
const float DISCOUNT4 = .32;
const double DEC = 100;
// Declare variables
double quantity;
double pricePerDisc;
double totalSavings;
double total;
char userInput;
float discount;
string discType;
string disc1 = "Ultimate Disc";
string disc2 = "Disc-Golf Disc";
// Display title
cout << "Welcome to the Flying-Disc Shop!" << "\n" << endl;
// Prompt the user for input
cout << "Enter 'u' for ultimate discs and 'g' for disc golf: ";
cin >> (userInput);
cout << endl;
switch (discType)
{
case 1: userInput=='u' || 'U';
discType = disc1;
pricePerDisc = ULTIMATE_RETAIL;
break;
case 2: userInput=='g' || 'G';
discType = disc2;
pricePerDisc = DISC_GOLF_RETAIL;
break;
default:
cout << "Invalid disc type." << endl;
return 0;
}
cout << "Enter the number of Ultimate Disc(s): ";
cin >> (quantity);
cout << endl;
cout << "------------Receipt------------" << endl;
if (quantity>5 && quantity<=9)
{
discount = DISCOUNT1 / DEC;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>10 && quantity<=19)
{
discount = DISCOUNT2;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>20 && quantity<=29)
{
discount = DISCOUNT3;
totalSavings = (pricePerDisc * quantity) * discount;
}
else if (quantity>= 30)
{
discount = DISCOUNT4;
}
totalSavings = (pricePerDisc * quantity) * discount;
total = quantity * pricePerDisc - totalSavings;
cout << "Disc Type: " << discType << endl;
cout << "Quantity: " << quantity << endl;
cout << "Pricer per Disc: " << "$ " << fixed << setprecision(2)
<< pricePerDisc << endl;
cout << "Total Savings: " << "$ " << "-" << fixed << setprecision(2)
<< totalSavings << endl;
cout << "Total: " << "$ " << total << fixed << setprecision(2) << endl;
}
CodePudding user response:
For single char responses, you can use the switch/case
statement:
switch (userInput)
{
case 'g':
case 'G':
/* ... */
break;
case 'u':
case 'U':
// ...
break;
default:
// ...
break;
}
A single character can be treated differently than a string. A string is usually consists of more than one character.