c++ - “while(getline(cin, name))”如何控制未知行数的查询?
问题描述
在 HackerRank 的问题中,有一个条件是查询的行数未知。问题的链接是:
我无法为每个测试用例解决问题,但我查看了解决方案,发现人们正在使用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))如何控制未知数量的查询行。
解决方案
std::cin
是输入流。
std::getline
从 读取一行std::cin
并将其写入name
. true
如果 this 没有错误,则返回等效项,false
否则返回。
因此,while
循环读取行,直到它失败或被打破。
您可以使用 强制失败std::cin.setstate(std::ios_base::failbit);
,也可以break
退出 for 循环。
推荐阅读
- sql-server - 如何检测 SQL Server 中查询执行的来源?
- android - 如何更改 apk 的方向,锁定在横向
- python - 在 python pandas 中使用 group by 方法的变量
- terraform - Tarraform iam 策略资源定义有条件地基于变量
- java - OnClickListener 代码运行但未命中断点(Android Studio)
- powershell - 替换powershell中的正则表达式值
- android - AMediaExtractor 在一种情况下会出错,而在另一种情况下不会,为什么?
- c++ - 如何正确实现其成员同时从 Cuda/C++ 中的主机和设备代码调用的类?
- ssis - SSIS 将文本限定符添加到导入的数据
- unity3d - Photon - OnLeftRoom 意外调用