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.
#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
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>
}