I need help with C++ exercise. Define a class CPerson that contains a char array
ID: 3676986 • Letter: I
Question
I need help with C++ exercise.
Define a class CPerson that contains a char array for a person’s name and an integer for age. Define public functions that are necessary for this exercise. Practice random file IO using this CPerson type as described below:
Create a file for random file IO. The file should be created if it doesn’t already exist, wiped out if it exists.
Write 100 persons to the file all with default name of “N/A” and default age of 0.
In a loop, ask input for 10 person’s name and age, and write each person to the file. Write the persons to the file position according to person’s age. For simplicity, when testing the program, enter different ages for these ten people. To prepare for step 7 below, make sure to enter John Smith and 56 as one of the person’s name and age.
Display each person from the file as long as the person’s age is not zero.
Search the file to see if there is a person with age 12. If so, display the person’s name and age. If not, display a message indicating there is no person age 12 in the file.
Update the age for John Smith to 57.
Display all the persons in the file whose age is not zero again.
Explanation / Answer
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
class CPerson{
private:
char *name;
int age;
public:
CPerson(){
name = "N/A";
age = 0;
}
CPerson(const char *name, int age){
setName(name);
setAge(age);
}
void setName(const char *name){
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
}
void setAge(int age){
this->age = age;
}
char *getName(){
return name;
}
int getAge(){
return age;
}
void printPerson(ostream &out){
out << name << " " << age << endl;
}
};
void printValidNames(string fileName){
ifstream in(fileName.c_str());
string name;
int age;
if(in.is_open()){
while(in >> name >> age){
if(age != 0)
cout << name << " " << age << endl;
}
in.close();
}
else{
cout << "can not open " << fileName << " to read" << endl;
}
}
int main(){
CPerson *arr = new CPerson[110];
string name;
int age;
for(int i = 100; i < 110; ++i){
cout << "Enter name: ";
cin >> name;
cout << "Enter age: ";
cin >> age;
arr[i].setName(name.c_str());
arr[i].setAge(age);
}
string fileName;
cout << "Enter file name: ";
cin >> fileName;
ofstream out(fileName);
if(out.is_open()){
for(int i = 0; i < 110; ++i){
arr[i].printPerson(out);
}
}
out.close();
printValidNames(fileName);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.