Function/while loop not working as intended

We recently started functions in my C++ class and for fun I tried to modify a program I had made to calculate miles per gallon using a function. Here's my program:
//User inputs date, location, mileage, and gallons; miles per gallon is computed and all data is output to a text file
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main()
{
char calculate_MPG();

calculate_MPG();

while (calculate_MPG() == 'y' || calculate_MPG() == 'Y')
{
calculate_MPG();
}
}

char calculate_MPG()
{
string date, location;
char confirm;
float miles, gallons, MPG;

cout << "Enter date (DD/MM/YY): ";
cin >> date;
cout << "Enter location: ";
cin >> location;
cout << "Enter number of miles: ";
cin >> miles;
cout << "Enter number of gallons: ";
cin >> gallons;
MPG = miles / gallons;
cout << "\nDate: " << date << "\nLocation: " << location << "\nMiles: " << miles
<< "\nGallons: " << gallons << setprecision(5) << "\nMPG: " << MPG;

ofstream myfile;
myfile.open ("MPG.txt", ios::app);
myfile << "\n" << setiosflags(ios::left) << setw(11) << date << setw(15) << location << setw(14) << miles << setw(14) << gallons << setprecision(5) << MPG;
myfile.close();

cout << "\n\nInput more data? (y/n) ";
cin >> confirm;
return confirm;
}


Everything works properly except for when I get to the end and it asks "Input more data? (y/n)" I type in n (or any letter besides y or Y), and it continues to loop. Why is that happening?

Also, if I remove the "|| calculate_MPG() == 'Y'" from the while condition, it works properly, but I don't understand why it would work differently.
the problem is, that you call the function a few times.
you use the function to check the users input, so in while (calculate_MPG() == 'y' || calculate_MPG() == 'Y') the function will run 2 times.

i recomment you change your code to:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

char calculate_MPG();

int main() {
	char input;
	do {
		input = calculate_MPG();
	} while (input=='Y' || input=='y');
	return 0;
}

char calculate_MPG() {
	your code here
}
Last edited on
Ok that makes sense. It works now. Thanks.
Topic archived. No new replies allowed.