Class function malfunctioning

Mar 17, 2009 at 12:20am
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 Mar 17, 2009 at 6:24pm
Mar 17, 2009 at 1:28am
For one thing your for() loop end condition is wrong; it should
be i < np.name.size().

Mar 17, 2009 at 7:08pm
For one thing your for() loop end condition is wrong; it should
be i < np.name.size().


Oops, thanks jsmith.


However, I have looked at the code again, and again and found no solution so I'm moving on, for now.
Mar 17, 2009 at 7:14pm
One question: are you familiar with STL maps?
Mar 17, 2009 at 7:25pm
are you familiar with STL maps?


No, not until you mentioned it. I'm reading the documentation, looks very promising. Thanks!
Mar 18, 2009 at 2:24am
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.

Mar 18, 2009 at 2:28am
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. :)

Linky:
http://www.cplusplus.com/forum/articles/6046/
Last edited on Mar 18, 2009 at 2:29am
Mar 18, 2009 at 2:50am
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 Mar 18, 2009 at 3:12am
Topic archived. No new replies allowed.