I am trying to write a program where functions are involved to validation user input and prints final sales total. A beginner thus working step-step. below is the product list and after it is my half written program.
................
cout << "White Cheese:\t\t\t$2.50\n";
cout << "White Egg:\t\t\t$2.70\n";//cannot be toasted
cout << "White Ham:\t\t\t$3.00\n" << endl;
cout << "Sourdough Cheese:\t\t$3.00\n";
cout << "Sourdough Egg:\t\t\t$3.20\n";//cannot be toasted
cout << "Sourdough Ham:\t\t\t$3.50\n" << endl;
cout << "Roll Cheese:\t\t\t$3.50\n";//cannot be toasted
cout << "Roll Egg:\t\t\t$3.70\n";//cannot be toasted
cout << "Roll Ham:\t\t\t$3.90\n\n" << endl << endl;//cannot be toasted
cout << "NOTE!!\t\nSandwiches can be toasted EXCEPT if they are Eggs or Rolls.\nExtra 50 cent charge for toasting\n";
...........................
my written program
#include <iostream>
#include <string>
using namespace std;
Asking customers or staff to type in the name of the sandwich is inviting trouble - spelling mistakes, mixing up upper and lower-case are bound to happen. It's better you spell out the sandwich names yourself and provide a menu to choose numbers corresponding to each sandwich type. That way there's less chances of errors and you can even check against invalid input (out of range numbers). So my suggestion would be on the lines of:
#include<iostream>
usingnamespace std;
int main(){
bool fQuit = false;
int choice;
while(!fQuit){
cout<<"Please choose one of the following sandwich options: "<<endl;
cout<<"1. White Cheese"<<endl;
cout<<"2. White Egg"<<endl;
cout<<"3. Exit"<<endl;
cin>>choice;
switch (choice){
case 1:{
cout<<"Please enter quantity: "<<endl;
int quantity;
cin>> quantity;
cout<<"Please choose: 1. Toasted (50 p per sandwich), 2. Non-toasted" <<endl;
int toasted;
cin>> toasted;
if (toasted ==1){
cout<<"Total cost is: "<<quantity * (2.50 + 0.50)<<endl;
}
else{
cout<<"Total cost is: "<<quantity * 2.50<<endl;
}
}
break;
case 2: {
cout<<"Please enter quantity: "<<endl;
int quantity;
cin>> quantity;
cout<<"Total cost is: "<<quantity * 2.70<<endl;
}
break;
case 3:
cout<<"You've chosen to exit, Goodbye!"<<endl;
fQuit = true;
break;
default:
cout<<"Please choose valid option number!"<<endl;
break;
}
}
}
A few things to note:
1. You could ask for the sandwich quantity outside of the switch, right after user inputs sandwich type, to avoid typing it for each sandwich option but then in case user wants to quit program they'd still have to enter some notional quantity to be able to do so;
2. Declaring variables like quantity, toasted inside cases means that each case needs to have braces { .. } surrounding it so as to scope the variables to the case itself;
3. If you're really paranoid you can even guard against someone choosing a number that is not 1 or 2 for the toasted option by having a nested switch