I have a little program I created just to practice but for some reason the compiler is skipping the cin "costPerGallon" inside "calculateCostPerMile" function.
Any idea why?
Does this has to do with the if statement I'm using?
cout << "Miles per Gallon Calculator" << endl;
cout << endl;
cout << "Please enter the number of gallons of gas your car can hold? " << endl;
cin >> gallons;
cout << endl;
cout << "Please enter the number of miles driven with a full tank? " << endl;
cin >> miles;
cout << endl;
mpg = miles / gallons;
cout << "You car will give you " << mpg << " miles per gallon " << endl;
cout << endl;
cout << "Would you like to calculate the cost for a trip? Please say 'Yes' or 'No' to continue..." << endl;
cin >> decision;
if (decision == true)
{
calculateCostPerMile();
}
else
{
cout << "Ok, thank you for using our calculator. Please hit enter to quit! " << endl;
}
return 0;
}
void calculateCostPerMile()
{
cout << "Please enter gas price "; cin >> costPerGallon; // the compiler is skiping this cin, why?
bool only takes 2 values, "true" or "false" or '1' or '0'. Not yes and no.
however true is just an alias for 1 and false an alias for 0.
if you want to use other values
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
char ch_in;
bool decision;
.....
cout << "Would you like to calculate the cost for a trip? Please say 'Y' or 'N' to continue..." << endl;
cin >> ch_in;
if (ch_in == 'Y' or ch_in == 'y')
decision = true;
else
decision = false;
if (decision == true)
calculateCostPerMile();
alternatively
1 2 3 4 5 6 7 8 9
char ch_in;
.....
cout << "Would you like to calculate the cost for a trip? Please say 'Y' or 'N' to continue..." << endl;
cin >> ch_in;
if (ch_in == 'Y' or ch_in == 'y')
calculateCostPerMile();
#include <iostream>
#include <cmath>
#include <string>
usingnamespace std;
float gallons, miles, mpg, costPerGallon, costPerMile;
string decision;
void calculateCostPerMile();
int main ()
{
cout << "Miles per Gallon Calculator" << endl;
cout << endl;
cout << "Please enter the number of gallons of gas your car can hold? " << endl;
cin >> gallons;
cout << endl;
cout << "Please enter the number of miles driven with a full tank? " << endl;
cin >> miles;
cout << endl;
mpg = miles / gallons;
cout << "You car will give you " << mpg << " miles per gallon " << endl;
cout << endl;
cout << "Would you like to calculate the cost for a trip? Please say 'Yes' or 'No' to continue..." << endl;
cin >> decision;
if (decision == "Yes" or decision == "yes")
{
calculateCostPerMile();
}
else
{
cout << "Ok, thank you for using our calculator. Please hit enter to quit! " << endl;
}
return 0;
}
void calculateCostPerMile()
{
cout << "Please enter gas price ";
cin >> costPerGallon;
cout << costPerGallon;
}