如何终止cin>>输入特定的单词/字母/数字/等

How to terminate cin>> input with specific word/letter/number/etc

本文关键字:gt 单词 何终止 字母 数字 cin 输入 终止      更新时间:2023-10-16

失败后如何再次使用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