Hey,
Been fiddling with this class called "name_pairs". It has two vectors, one holds names and the other the accompanying age.
Here is the code:
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
|
class name_pairs{
protected:
vector<string> name;
vector<int> age;
public:
void read_names(){
string s;
getline(cin,s);
name.push_back(s);
read_age();
}
void read_age(){
int a;
cin >> a;
age.push_back(a);
}
void print_np(name_pairs &np){
for(int i = 0; i<=np.name.size();i++)
cout << np.name[i] << ", " << np.age[i] << endl;
}
};
|
The idea behind read_names is that when a name is entered, one is prompted for an accompanying age. However, if I try this:
1 2 3 4 5 6
|
name_pairs np;
np.read_names();
np.read_names();
np.print_np(np);
|
It only stores the first name and age correctly. If I try entering:
Joe
18
Bob
Stops reading and prints:
Joe, 18
, 4078844
On the other hand, if I try feeding it:
16
17
18
It prints;
16, 17
, 18
Any hints would be much appreciated.
Last edited on
For one thing your for() loop end condition is wrong; it should
be i < np.name.size().
One question: are you familiar with STL maps?
Had a look at map:
Hit the same problem, only being able to store the first pair. Producing same ouput as in the initial post.
Last edited on
Right, the problem has to do with mixing getline and operator>>. I'm just addressing the fact that you are manually trying to create a map. :) |
*Does happy dance*
Thanks alot mate! It's alive, it's alive!
Furthermore, I now know of a useful container. Twice blessed be I.
Last edited on