简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM