Load data using member function.
Sep 14, 2016 at 1:27am UTC
The person class should have the following functions:
• Constructor(s)
• Destructor - optional
• Get - read first name, last name, and age from an input stream
• Put - write last name, first name, and age to an output stream
I was trying to implement the get() so that it could read the text from a file, but I'm kinda stuck.
person.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <iostream>
#include <string>
using namespace std;
#include "person.h";
//Empty person constructor.
person::person()
{ fName = "Default" ;
lName = "Default" ;
age = 0;
}
// Input
bool person::get(istream &in)
{ in >> fName >> lName >> age;
return (in.good());
}
// Output
void person::put(ostream &out)
{ out << lName << fName << age;
}
person.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
using namespace std;
// Person header.h
class person
{ public :
person(); // Empty constructor.
bool get(istream &); // Read input from file.
void put(ostream &); // Write to an output stream.
// Operators to compare.
bool operator < (person); //lesser.
bool operator > (person); //greater.
bool operator == (person); //equal.
string fName; //First Name.
string lName; //Last Name.
int age; //Age.
};
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
#include "person.h"
void main()
{
int i,x;
string name;
fstream infile;
person info[20];
//Open File.
cout << "Enter the file name: " ;
cin >> name;
infile.open(name.data(),ios::in);
// loop
while (!infile.eof())
{
if (infile.good())
{
for (i = 0; i < 20; i++)
{
info[i].get(cin);
}
};
};
infile.close();
}
It freezes whenever I try to use get() to load input from a file to an array. However, it works when I do:
infile >> info[i].lName >> info[i].fName >> info[i].age;
Here is my data from the file.
1 2 3 4 5 6 7 8 9 10
Ann Christensen 70
Carlos Morales 68
David Bowman 45
Frank Bowman 37
John Bowman 30
Kathleen Gueller 34
Mark Bowman 42
Mark Bowman 13
Richard Bowman 47
Susan Cox 36
Thank you.
Last edited on Sep 14, 2016 at 1:28am UTC
Topic archived. No new replies allowed.