Help appreciated - Pass by reference
Mar 12, 2015 at 12:43am UTC
Hey fun2code, this is my current code below. Everything is working great, but I am not sure why it is printing the Main Menu twice after using the Input function. Why is it doing that?
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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
#include <iostream>
using namespace std;
const double TAXPERMILE = .05;
const double TAXPERGAL = .529;
void Input(double & MilesDriven, double & GalsUsed);
void CalcAndDisplay(double & MilesDriven, double & GalsUsed);
int main()
{
double MilesDriven = 0;
double GalsUsed = 0;
char loop = 'y' ;
char menu;
while (loop == 'y' )
{
cout << "Main Menu" << endl;
cout << "(E)nter the miles driven and number of gals used." << endl;
cout << "(C)alculate the two tax rates and display them." << endl;
cout << "(Q)uit the program." << endl;
cout << "Enter a (E), (C) or (Q) only." << endl;
cin.get(menu);
switch (menu)
{
case 'e' :
case 'E' :
Input(MilesDriven, GalsUsed);
break ;
case 'c' :
case 'C' :
CalcAndDisplay(MilesDriven, GalsUsed);
break ;
case 'q' :
case 'Q' :
loop = 'n' ;
break ;
}
}
system("cls" );
return 0;
}
void CalcAndDisplay(double & MilesDriven, double &GalsUsed)
{
double TotalTaxDrivingMiles = 0;
double TotalTaxFuel = 0;
cout << "Enter the number of miles driven:" << endl;
cin >> MilesDriven;
cin.ignore();
cout << "Enter the number of gallons used:" << endl;
cin >> GalsUsed;
cin.ignore();
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
TotalTaxDrivingMiles = TAXPERMILE * MilesDriven;
TotalTaxFuel = TAXPERGAL * GalsUsed;
cout << "The total of tax per mile is= " << TotalTaxDrivingMiles << endl;
cout << "The total of tax per gallon is= " << TotalTaxFuel << endl;
system("pause" );
system("cls" );
}
void Input(double &MilesDriven, double &GalsUsed)
{
bool invalid = false ;
do
{
invalid = false ;
cout << "Enter the amount of miles driven: " << endl;
cin >> MilesDriven;
cout << "Enter the number of gallons used: " << endl;
cin >> GalsUsed;
if (cin.fail())
{
invalid = true ;
cin.clear();
cin.ignore();
}
} while (invalid);
cout << "The values for miles driven and gallons of fuel used has been entered! " << endl;
cout << "Miles driven = " << MilesDriven << endl;
cout << "Gallons of fuel used = " << GalsUsed << endl;
system("pause" );
system("cls" );
}
Mar 27, 2015 at 7:31am UTC
The problem is on line 25: operator >>
leaves the new line character in the stream which is extracted the next time you call get(...)
replace line 25 with cin >> menu;
Topic archived. No new replies allowed.