Class

Hi everyone. i want to create a class for student registration for example one student can register many subject and Created this class , but i Have problem because my output isn't correct

#include<iostream>
#include<vector>
#include<string>
const int size = 3;
using namespace std;

class Student
{

private:
string name;
vector<string>subject;
public:
void setName();
void getName();
};
int main()
{
Student stu;
vector<Student>stud;
for ( int i = 0 ; i < size ; i++)
{
stu.setName();
stud.push_back(stu);

}

for ( int i = 0 ; i < size ; i++)
stud[i].getName() ;
return 0;

}

void Student::setName()
{
int size; //
string temp;
cout << "\n Please Enter Name : ";
cin >> name;
cout << "\n how many subject : ";
cin >> size;
for ( int i = 0 ; i < size ; i++)
{
cin >> temp;
subject.push_back(temp);
}
}
void Student::getName()
{
cout << endl;
cout << name << endl ;
for ( int i = 0 ; i < subject.size(); i++)
cout << subject[i] << endl;
}


////////////this my out put //////

redhat
c++1
c++2
blackhat
c++1
c++2
java1
java2
java3

blackhat doesn't have c++1,c++2 but subject from redhat add to blackhat

tnx



Well, it's because you don't clear the vector when you use setName(), yet you still use push_back(). So you keep adding data, but you don't clear any of the old stuff that you don't want in your temporary variable.

Also, [code] tags would be highly appreciated in the future. :)

-Albatross
tnx . how can i solve my problem
Fix the problem Albatross pointed out; that will fix your problem.
I'd love to give you more help, however it would have been a lot easier if I didn't have to figure out the line numbers.

Somewhere between line 35 and 36, you'll want to use one of subject's member functions (just one) to clear the whole vector. I named it within the first ten words of my previous post, so, look around the vector reference and my post and you'll eventually what to use to clear the vector. :)

http://cplusplus.com/reference/stl/vector/

-Albatross
tnx albatorss
i changed my function to this , and its work
void Student::setName()
{
int size;
string temp;
cout << "\n Please Enter Name : ";
cin >> name;
cout << "\n how many subject : ";
cin >> size;
subject.clear();
for ( int i = 0 ; i < size ; i++)
{
cin >> temp;
subject.push_back(temp);
}

}
i read clear in vector drop all data but i don't understand what's happen when i used clear
Clear does exactly what it says it does. :)

What clear does is erases all the elements of the vector and then drops them, leaving the vector empty. So the leftover data you had from pushing_back() the earlier stuff (namely "c++1" and "c++2") is erased, so that when you push_back() stu with the new data, the old stuff doesn't go with it.

-Albatross
Topic archived. No new replies allowed.