mercredi 2 mars 2016

Class holding vector of classes

I am learning OOP in c++ so i tried to practise a little. I want to create a "database " (using objcets) of class and its students. I created a class for a student. Each have a name and age.

class Ziak{

public:

    Ziak(int,string);
    int getAge(){
        return age;
    }
    string getName(){
        return name;
    }

private:

    int age;
    string name;

};

Ziak::Ziak(int age,string name){
    this->age=age;
    this->name=name;
}

And i created a class of a Classroom , each is represented by its name , teacher and students ( vector of objects )

class Trieda{

public:
    Trieda(string,string);
    void fillStudents(){
        while(1){
            int age;
            string name;
            cout << "Name: ";
            getline(cin,name);
            cout << "Age: ";
            cin >> age;
            Ziak newStudent(age,name);
            n.push_back(newStudent);
            if(cin.eof()){
                break;
            }
        }
    }
    string getTeacher(){
        return ucitel;
    }
    string getNamesOfStudents(){
        for( unsigned i = 0; i < n.size(); i++){
            cout << "hey " << n[i].getName() << endl;
        }
    }

protected:
    vector<Ziak> n;
    string nazov;
    string ucitel;
};
Trieda::Trieda(string nazov,string ucitel){
    this->nazov=nazov;
    this->ucitel=ucitel;
}

and i am just calling its metods in main

int main()
{
    Trieda newClass("4A","Ms Foster");
    newClass.fillStudents();
    newClass.getNamesOfStudents();
    return 0;
}

What my problem here is method fillStudents() is starts pretty nice = output is

Name: // insert name
Age : // insert age

second iteration looks worse.

Name:Age: // insert something

and third iteration is infinite loop printing Name:Age till the end of the world. I tried to just use cin >> name instead of getline , e.g

void fillStudents(){
        while(1){
            int age;
            string name;
            cout << "Name: ";
            cin >> name;
            /*getline(cin,name);*/
            cout << "Age: ";

            cin >> age;

            if(cin.eof()){
                break;
            }else{
                Ziak newStudent(age,name);
                n.push_back(newStudent);
            }
            cin.clear();

        }
    }

It quite works. But it works like this

Name: // insert name
Age : // insert age
// it works till the last one when i press ctrl+Z as eof ( currently on windows)
it outputs Age: Hey + first name ....
Hey name 2 // and so on , then it crashes

What causes this? I suspect it could be something with buffer not being cleared but i tried cin.clear() and it happened too. How can i implement it with getline ( i wanted full name as name inptut e.g John Wicked ).

I am trying to figure it out but im just begginer with c++ so my knowledge is limited so far.

Aucun commentaire:

Enregistrer un commentaire