Advertisement
NickG

Gas Calc - gas.cpp

Feb 29th, 2012
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 KB | None | 0 0
  1. //NickG
  2. //Gas Calculator
  3.  
  4. #include <iostream>
  5. #include <iomanip>
  6. using namespace std;
  7.  
  8. void validate (float* data) {
  9. while(cin.fail()) { //Input validation loop
  10.    cin.clear();  //Clear flags
  11.    cin.ignore();  //Clear input buffer
  12.    cout<<"Invalid Input - Please input a number:";
  13.    cin>>(*data);
  14.    }
  15. }
  16.  
  17. int main () {
  18. float gallons, miles, price, totalg, totalp, totalm, totalt;
  19. char response;
  20. cout << fixed << setprecision (2); //Set the output precision and output format
  21.  
  22. do { //Primary loop start
  23.    do {
  24.       if (gallons!=0)
  25.       {cout << "Enter the gallons used:";}
  26.       else //If gallons is 0, ask for a non-zero number
  27.       {cout << "Enter a non-zero number:";}
  28.       cin >> gallons;
  29.       validate (&gallons);
  30.       } while (gallons==0);
  31.    cout << "Enter the miles driven:";
  32.    cin >> miles;
  33.    validate (&miles);
  34.    cout << "Enter the price/gallon of gas:$";
  35.    cin >> price;
  36.    validate (&price);
  37.    
  38.    totalg+=gallons; //increment total gallons
  39.    totalp+=(price*gallons); //increment total price
  40.    totalm+=miles; //increment total miles
  41.    totalt++; //increment total trips
  42.    cout <<endl << "The mpg for this trip was " << miles/gallons << endl;
  43.    cout << "The cost of this trip was $" << price*gallons << endl;
  44.    
  45.    do { //Response loop
  46.       cout << "Would you like to calculate another trip? (y/n)";
  47.       cin >> response;
  48.       } while ((response!='y')&&(response!='Y')&&(response!='n')&&(response!='N')); //Wait for valid input
  49.    cout << endl;
  50.    } while ((response=='y')||(response=='Y')); //Primary loop end
  51. cout << "Total miles traveled: " << totalm <<endl; //Print averages
  52. cout << "Total price of trips: $" << totalp <<endl;
  53. cout << "Total gallons of gas used: " << totalg <<endl;
  54. cout << "The average miles driven was: " << totalm/totalt <<endl;
  55. cout << "The average mpg was: " << totalm/totalg <<endl;
  56. cout << "The average price of a trip was: $" << totalp/totalt <<endl;
  57. #if defined (__WIN32__) || defined (__WIN32)
  58. cout << "Press any key to continue...";
  59. cin.ignore(255,'/n');
  60. cin.get();
  61. #endif
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement