Hi, I'm working on a mileage calculator to better understand functions and objects and need some help figuring out how to write data to a file so I can call it up later.
Specifically, I'm trying to write a function I can call. Here's are my files so far. It's just not working, it seems to think "ofstream" is an undeclared identifier.
Thanks for any advise!
//============= MAIN FILE ==============================================
mileage.cpp
int main(int currentmiles, int previousmiles, int mpg)
{
Car car1; //instantiate a car
int g, p, c;
cout << "Input miles before last fillup: ";
cin >> p;
cout << "Enter current miles: ";
cin >> c;
cout << "Input amount of gas put in: ";
cin >> g;
if (!car1.setPreviousmiles(p)) //call function to set previous miles
cout << "Invalid previous miles data entered." << endl;
else if(!car1.setCurrentmiles(c, p)) //call function to set current miles
cout << "Invalid current miles data entered." << endl;
else if(!car1.setGallonsinput(g)) //call function to set gallons put in
cout << "Invalid gallons data entered." << endl;
else
cout << "Your mpg is: " << car1.getMpg() << endl; //call function to print mileage
class Car
{
private:
int currentmiles, previousmiles, milesdriven, gallonsinput, mpg;
// string make, model;
public:
bool setCurrentmiles(int c, int p);
bool setPreviousmiles(int p);
bool setGallonsinput(int g);
int getMpg();
int saveData(int mpg, int currentmiles);
};
#endif
You need to include "using namespace std" in your car.h file for it to use ofstream/ifstream or you can do std::ofstream.
You also don't need to #include <fstream> in both the .cpp file and the .h file. Just the .h file should be fine as the .cpp file is reading from that.
Finally your saveData function doesn't look like it is working correctly. You are passing in the mpg and current miles which are defined in main and are never assigned a value. You need to pass in car1.getMpg() and a function to return the current miles to your saveData function instead.
(You also have a syntax error in your saveData function)
Thanks for your help, I've changed the first two things you pointed out and they work great, but I've spent all morning trying to figure out how to pass a function and can't seem to get it. From what I've read so far I need to pass a pointer to the function, is that correct? I've tried and can't get it to work. Any help is greatly appreciated.