I have this exercise from Programming principles and practice using C++ by B. Stroustrup:
- Design and implement a
Name_pairsclass holding (name,age) pairs where name is astringand age is adouble. Represent that as avector<string>(calledname) and avector<double>(calledage) member. Provide an input operationread_names()that reads a series of names. Provide aread_ ages()operation that prompts the user for an age for each name. Provide aprint()operation that prints out the (name[i],age[i]) pairs (one per line) in the order determined by thenamevector. Provide asort()operation that sorts thenamevector in alphabetical order and reorganizes theagevector to match. Implement all "operations" as member functions. Test the class (of course: test early and often).
Here I show the part that causes the problem only for the brevity sake:
std::istream& Name_pairs::read_names(std::istream& in){
for(std::string str; in >> str; )
name.push_back(str);
in.clear();
in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// the following lines are added just for testing the stream state
int x;
std::cout << "x: ";
std::cin >> x;
std::cout << x << '\n';
return in;
}
Now if I call the member function:
Name_pairs{}.read_names(std::cin);
I get prompted to enter names until I hit EOF (Ctrl+D). At that moment I follow it by clear and ignore to reset the input buffer. But I am not prompted to input x!!?
I've seen some suggestions that I should trigger a constant string as an exit mark like
std::string quit = "quit; if(str == quit) break;but I don't want this; I want to useCtrl+dthen get input again. In other words can I use the input stream after pressingCtrl+D?I've tried the very program on windows 10 and Code::blocks for windows and it worked fine! I press
Ctrl+D; the loop breaks then I am prompted to inputx.So how could I fix the problem? thanks