首页 > 解决方案 > “while(getline(cin, name))”如何控制未知行数的查询?

问题描述

在 HackerRank 的问题中,有一个条件是查询的行数未知。问题的链接是:

第 8 天:字典和地图

我无法为每个测试用例解决问题,但我查看了解决方案,发现人们正在使用while(getline(cin, name))来控制未知数量的查询行,如下所示:

    string name;
    while(getline(cin, name))
    {
        std::map<string, string>::iterator it;
        it = phoneList.find(name);
        if (it == phoneList.end()){
            cout << "Not found" << endl;
        } else {
            cout << name << "=" << it->second << endl;
        }
    }

现在,我不知道while(getline(cin, name))如何控制未知数量的查询行

标签: c++while-loopgetline

解决方案


std::cin是输入流。

std::getline从 读取一行std::cin并将其写入name. true如果 this 没有错误,则返回等效项,false否则返回。

因此,while循环读取行,直到它失败或被打破。

您可以使用 强制失败std::cin.setstate(std::ios_base::failbit);,也可以break退出 for 循环。


推荐阅读