如何终止cin>>输入特定的单词/字母/数字/等
How to terminate cin>> input with specific word/letter/number/etc
失败后如何再次使用cin>>或如何退出while(cin>>some_string>>some_int)
是否合法,以便cin>>可以再次使用?
练习如下:用名称和年龄填充2个向量(1个字符串和1个int),通过行"不再"终止输入,要求程序输出相应年龄的名称(或"找不到名称")。我的问题是cin>>:当我输入"不再"时,再次使用cin>>的任何尝试都是失败的。
代码:
{
vector<string>name_s;
vector<int>age_s;
int age = 0,checker=0;
string name;
while( cin>>name>>age) //input of name and age
{
name_s.push_back(name); //filling vectors
age_s.push_back(age);
}
string name_check;
cout<<"nEnter a name you want to check : ";
cin>>name_check;
for(int i =0;i<name_s.size();++i)
{
if(name==name_s[i])
{
cout<<"n"<<name_check<<", "<<age_s[i]<<"n";
++checker;
}
}
if(checker<1)
cout<<"nName not found.n";
system("PAUSE");
}
"通过线路"no more"
终止输入"
你可以通过线条而不是文字来阅读输入:
#include <iostream>
#include <string>
#include <sstream>
...
std::string line;
while (std::getline(std::cin, line) && line != "no more") {
if (line.empty()) ; // TODO: line might be empty
std::istringstream is(line);
std::string name;
int age;
if (is >> name && is >> age) { /* TODO: store new data */ }
}
如果你想处理这个no more
后面有额外字符的情况,那么你可以使用line.substr(0,7) != "no more"
,如果你只想知道no more
是否在行内,而不一定在开头,你可以这样做:line.find("no more") != std::string::npos
相关文章:
- 文本文件中的单词链表
- 在指针的帮助下,文本文件中单词的频率
- 如何根据单词在文本中出现的概率输出单词
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- EASTL矢量<向量<int>>连续的
- 如何用for循环在c++中生成单词三角形
- 将数字转换为单词
- 使用if-else将数字转换为单词
- C++-字符串是否包含一个带有简单循环的单词
- 使用单词"not"作为C ++类的名称会导致VS2019错误
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- C++为一串单词添加空格
- 在C++中查找(奇怪的)字符串中的单词
- 当字符串是某个单词时给出输出?
- 当您在此单词中搜索单词时调整字符数组的大小?
- 数每个单词的元音
- 我们如何在文本文件中找到C++中的几个单词?
- 使用 BFS 的单词梯 2