#include <iostream>
#include <cctype>
#include <string>
#include <iomanip>
char get_choice()
{
std::cout << "\nSelect an option\n\n""a. Add an item to the cart:\n""t. Total:\n""q. Quit\n\n" ;
char choice ;
std::cin >> choice ;
return std::tolower(choice) ; // http://www.cplusplus.com/reference/cctype/tolower/
}
void get_item( std::string& name, double& price )
{
// there is a new line left in the input buffer after the formatted input in
// get_choice(). we need to throw that away, before the next unformatted input
// see: http://www.cplusplus.com/forum/general/69685/#msg372532
std::cin.ignore( 1000, '\n' ) ; // http://www.cplusplus.com/reference/istream/istream/ignore/
std::cout << "enter item name: " ;
std::getline( std::cin, name ) ;
std::cout << "enter price of '" << name << "': " ;
std::cin >> price ;
// TODO: the user may not enter a valid number.
// for instance, the user may enter 'abcd'
// we may need to add a fix for that.
}
int main()
{
std::cout << std::fixed << std::setprecision(2) ;
double total = 0 ;
char choice ;
while( ( choice = get_choice() ) != 'q' )
{
std::string name ;
double price = 0 ;
switch(choice)
{
case'a' :
get_item( name, price ) ;
std::cout << "item: '" << name << "' price: " << price << '\n' ;
total += price ;
break ;
case't' :
std::cout << "subtotal: " << total << '\n' ;
break ;
default:
std::cout << "invalid input.\n" ;
}
}
std::cout << "grand total: " << total << '\n' ;
}