Sunday, 8 September 2013

Consecutive string input using std::cin

Consecutive string input using std::cin

I have a map where I want to input a last name, and then subsequently
enter first names of the family members. I want to hit end of file after
entering the first names and then repeat the process.
The following is my code. I am trying to input an end of file, clear it
and go to the outer loop. However, when I input end of file it exits both
loops. What can I do to prevent this?
Also I know that I can write the program in a different way but I would
like to know how I can fix the current code.
#include <iostream>
#include <map>
#include <vector>
int main()
{
std::string last, children;
std::map<std::string, std::vector<std::string>> family;
while(std::cin >> last) {
while(std::cin >> children) {
family[last].push_back(children);
}
std::cin.clear(~std::istream::eofbit);
}
for(const auto &l:family) {
std::cout << l.first << std::endl;
for(const auto &c:l.second)
std::cout << c << " ";
std::cout << std::endl;
}
return 0;

No comments:

Post a Comment