1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
#include <iostream>
#include <string>
#include <iomanip>
enum vehicle_class { ECONOMY=0, SPORT=1, LUXURY=2, VAN=3, TRUCK=4 };
const int N = TRUCK+1 ; // number of vehicle types
const std::string vehicle_name[N] = { "Economy", "Sport", "Luxury", "Van", "Truck" } ;
const double daily_cost[N] = { 45.90, 57.75, 85.50, 55.00, 55.00 } ;
const int free_miles[N] = { 40, 120, 150, 150, 150 } ;
const double overage_rate[N] = { 0.25, 0.40, 0.50, 0.50, 0.50 } ;
vehicle_class get_vehicle_class()
{
std::cout << "vehicle classes:\n-------------\n" ;
std::string valid_chars ;
for( const std::string& name : vehicle_name )
{
std::cout << name.front() << ". " << name << '\n' ;
valid_chars += name.front() ;
}
std::cout << "\nEnter the class of the vehicle [one of " << valid_chars << "]: " ;
char vc ;
std::cin >> vc ;
vc = std::toupper( (unsigned char)vc ) ;
for( int i = 0 ; i<N ; ++i )
if( vehicle_name[i].front() == vc ) return vehicle_class(i) ;
std::cout << "invalid vehicle class. try again\n\n" ;
return get_vehicle_class() ;
}
double get_miles()
{
const double min_miles = 1 ;
const double max_miles = 812 ;
std::cout << "Please enter the estimated miles ("
<< min_miles << " to " << max_miles << "): ";
double miles ;
if( std::cin >> miles )
{
if( miles >= min_miles && miles <= max_miles ) return miles ; // valid input, return it
else std::cout << "invalid value for estimated miles. try again\n" ;
}
else
{
std::cout << "error: non-numeric input. try again\n" ;
std::cin.clear() ; // clear the failed stated
std::cin.ignore( 1000, '\n' ) ; // throw the bad input line away
}
return get_miles() ; // try again
}
double cost_for_the_day( vehicle_class selected_vehicle, double miles )
{
double cost = daily_cost[selected_vehicle] ;
const double free_dist = free_miles[selected_vehicle] ;
if( miles > free_dist ) cost += (miles-free_dist) * overage_rate[selected_vehicle] ;
return cost ;
}
int main()
{
const vehicle_class vc = get_vehicle_class() ;
const double miles = get_miles() ;
const double cost = cost_for_the_day( vc, miles ) ;
std::cout << "vehicle '" << vehicle_name[vc] << "' costs GBP "
<< std::fixed << std::setprecision(2) << cost
<< " for " << miles << " miles.\n" ;
}
|