1

我有一个map我想输入姓氏的地方,然后输入家庭成员的名字。我想在输入名字后打到文件结尾,然后重复这个过程。

以下是我的代码。我正在尝试输入文件结尾,将其清除并转到外循环。但是,当我输入文件结尾时,它会退出两个循环。我能做些什么来防止这种情况发生?

我也知道我可以用不同的方式编写程序,但我想知道如何修复当前代码。

#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;
4

1 回答 1

0

std::ios::clear()以错误的方式使用。将其设置为not eofbit会导致设置其他失败位。去掉传给clear()或使用的参数std::ios::goodbit,同理,从EOF中恢复cin。

参考:ios::clear

于 2013-09-08T19:29:22.530 回答