0
#include <iostream>             
#include <fstream>
#include <string>       
using namespace std;

class Name
{
public:
    string firstname;
    string lastname;

};

class Adress
{
public:
    string housenum;
    string stname;
};

class Person
{
    Name name;
    Adress adress;
    public:
    void readData(ifstream &cfile);
    void printData(ofstream &outfile);

};
void read(Person);                    // function prototypes
void print(Person);

int main()
{
    Person jeffrey;
    cout << " Please enter a first and last name " << endl;
    read(jeffrey);
    print(jeffrey);

    return 0;
}

I am trying to get the function read to call the member function readData to read in the name. But when the program is compiled and run. I get prompted to enter the name , but then after that it does not output it. It looks like it outputs a null string. It works and outputs when readData and printData are called directly from main but not when called from the other functions. Help Please.

void read(Person M)
{
    ifstream cfile("con");
    M.readData(cfile);
    cfile.close();
    return;
}
void print(Person M)
{
    ofstream outfile("con");
    M.printData(outfile);
    outfile.close();
    return;
}
void Person::readData(ifstream &cfile)
{
    cfile >> name.firstname;

    cfile >> name.lastname;

    return;
}

void Person::printData(ofstream &outfile)
{
    outfile << name.firstname << endl;
    outfile << name.lastname << endl;
    return;
}
user4581301
  • 33,082
  • 7
  • 33
  • 54
pharos23
  • 11
  • 3
  • 1
    Read up on *passing parameters by-reference* as opposed to *passing by-value*. You also don't need such a big example to show this. [See this](http://coliru.stacked-crooked.com/a/9e09427e7d7a7970) – PaulMcKenzie Sep 30 '17 at 01:02
  • Unrelated: idiomatically, `readData` and `printData` would be `istream & operator>>(istream &, Person &)` and `ostream & operator>>(ostream &, const Person &)`, respectively. A bunch of good reasons for this. 1. `infile >> someperson;` is pretty easy to write. 2. Easy error checking (`if(infile >> someperson) // do stuff with someperson;`) 3. you can use it with any stream, not just files. More information here: https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading – user4581301 Sep 30 '17 at 01:17
  • 1
    since you are passing the obejcts by value to the `read` function, you only modify the copy of the objectwhich is local to the function. The other copy in the global scope does not get any change. So, pass it by reference or as a pointer. – Serge Sep 30 '17 at 01:22

0 Answers0