Problem with basic input loop

Greetings. The problem I am having is with my read_ages function. It just loops without pausing to let me enter the data. This must be something obvious but I just can't see it.

Here is my code, followed by a sample output.

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include "..\std_lib_facilities.h"

class Name_pairs
{
private:
    vector<string> names;
    vector<int> ages;

public:
    void read_names();
    void read_ages();
    void print();
};

void Name_pairs::read_names()
{
    cout << "enter some names\n";
    string s;
    while( cin >> s )
    {
        names.push_back( s );
    }
}

void Name_pairs::read_ages()
{
    int age;
    for( vector<string>::size_type i=0; i<names.size(); ++i )
    {
        cout << "enter the age for " << names[i] << ": ";
        cin >> age;
        ages.push_back( age );
    }
}

void Name_pairs::print()
{
    for( vector<int>::size_type i = 0; i < names.size(); ++i )
    {
        cout << names[i] << "\t" << ages[i] << "\n";
    }
}

int main()
{
    Name_pairs np;
    np.read_names();
    np.read_ages();
    np.print();

    return 0;
}


enter some names
Fred
Bob
Jo
Jen
^Z
enter the age for Fred: enter the age for Bob: enter the age for Jo: enter the a
ge for Jen: Fred 6029362
Bob 6029362
Jo 6029362
Jen 6029362


Last edited on
When you enter in something that isn't a string in the read_names() function the cin stream goes into a failed state. Once in a failed state it will ignore all future commands until cleared.

1
2
3
4
5
6
7
8
9
10
11
12
void Name_pairs::read_names()
{
    cout << "enter some names\n";
    string s;
    while( cin >> s )
    {
        names.push_back( s );
    }

    cin.clear();   // clear failed state
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');   // Make sure the buffer is empty, might need to include <limits> 
}


http://www.cplusplus.com/reference/ios/ios/clear/
Thanks. I can live with that mistake.
Topic archived. No new replies allowed.