Moblie Apps with Qt: Xuan's solution hw1

From CSclasswiki
Jump to: navigation, search
#include <iostream>
#include <string>
using namespace::std;

class Person{
private:
     string first;
     int age;
     string food;
public:
     Person(string fir,int a,string f);
     Person();
     ~Person();
     int getAge();
     string getName();
     string getFood();
     void init(string fir,int a,string f);
};
Person::Person(){
    init(" ",0," ");
}

Person::Person(string fir,int a,string f){
    init(fir,a,f);
}
int Person::getAge(){
    return age;
}
string Person::getName(){
    return first;
}
string Person::getFood(){
    return food;
}

void Person::init(string fir,int a,string f){
    first=fir;
    age=a;
    food=f;
}
Person::~Person(){}


class Record{
private:
    Person *pArr;
    int size;
    int currentNum;
public:
    Record(int s);
    Record();
    ~Record();
    void init(int s);
    void addPerson(Person p);
    void getYoung();
    void getSameFood(string foo);
    void print();
};
void Record::print(){
   for (int i=0;i<size;i++){
       cout<<pArr[i].getName()<< ", "<<pArr[i].getAge()<< ", "<<pArr[i].getFood()<<endl;
   }
}

Record::Record(){
    init(1);
}

Record::Record(int s){
    init(s);
}

void Record::init(int s){
    size=s;
    currentNum=0;
    pArr=new Person[s];
}

Record::~Record(){
}

void Record::addPerson(Person p){
    pArr[currentNum++]=p;
}
void Record::getYoung(){
    Person *y;
    y = &pArr[0];
    for (int i=0;i<size;i++){
        if (y->getAge()>pArr[i].getAge()){
            y=&pArr[i];
        }
    }
    cout<<"The youngest person is: "<<y->getName()<<endl;
}
void Record::getSameFood(string foo){
    for (int i=0;i<size;i++){
        if (pArr[i].getFood().find(foo)!=string::npos){
            cout<<pArr[i].getName()<<" also likes "<< foo;
        }
    }
}

int main(){
    cout<<"How many persons' record do you have? ";
    int num;
    cin>>num;
    Record rec=Record(num);
    for (int i=0;i<num;i++){
       string firstName,food;
       int age;
       cout<<"Enter a name: ";
       cin>>firstName;
       cout<<"Give me an age: ";
       cin>>age;
       cout<<"Give me his/her favorite food, separated by , :";
       getline(cin,food);
       rec.addPerson(Person(firstName,age,food));
    }
    rec.print();
    rec.getYoung();
    cout<<"Enter your favorite food: ";
    string fav;
    cin>>fav;
    rec.getSameFood(fav+",");
    return 0;
}