Mike Vincent
Mike Vincent

Reputation: 13

Reading data from a file refuses to populate object

I am reading data from a file and one of my two objects is populating correctly, while the other does not. This is happening despite the objects are using essentially the same functions and reading from essentially the same files.

#include "DietPlan.h"
#include "exercisePlan.h"

int main()
{
ifstream dietPlansIn("dietPlans.txt");
ifstream exercisePlansIn("exercisePlans.txt");
DietPlan tacos[7];
ExercisePlan burritos[7];


for (int i = 0; i < 7; i++) {
    dietPlansIn >> tacos[i];
    exercisePlansIn >> burritos[i];
}
}

#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

class DietPlan
{
public:
void setGoal(int newGoal) { goal = newGoal; }
void setName(string newName) { name = newName; }
void setDate(string newDate) { date = newDate; }

friend istream& operator >> (istream& in, DietPlan& D) {
    string line;

    getline(in, line);
    D.setName(line);

    getline(in, line);
    D.setGoal(atoi(line.c_str()));

    getline(in, line);
    D.setDate(line);

    getline(in, line);

    return in;
}

private:
int goal;
string name;
string date;
};

#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

class ExercisePlan
{
public:
void setGoal(int newGoal) { goal = newGoal; }
void setName(string newName) { name = newName; }
void setDate(string newDate) { date = newDate; }

friend istream& operator>> (istream& in, ExercisePlan E) {
    string line;

    getline(in, line);
    E.setName(line);

    getline(in, line);
    E.setGoal(atoi(line.c_str()));

    getline(in, line);
    E.setDate(line);

    getline(in, line);

    return in;
}
private:
int goal;
string name;
string date;
};

I would expect that both tacos and burritos from main get populated correctly, but instead only tacos does. Burritos refuses to populate.

Upvotes: 1

Views: 52

Answers (1)

john
john

Reputation: 87959

You need to pass by reference

istream& operator>> (istream& in, ExercisePlan& E)

not

istream& operator>> (istream& in, ExercisePlan E)

The way you have written it the changes happen to the local variable E in your operator>> not to the array you are trying to populate.

Sometimes you just stare at code and you can't see the obvious.

Upvotes: 3

Related Questions