繁体   English   中英

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

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

失败后如何再次使用cin >>或如何合法退出while(cin>>some_string>>some_int)以便再次使用cin >>?

练习是这样的:用名称和年龄填充2个向量(1个字符串和1个int),以“ no more”行终止输入,询问程序需要输出相应年龄的名称(或“找不到名称”) “)。 我的问题是与cin >>:当我输入“ no more”时,再次使用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"

Yould可以按行而不是按单词读取输入内容:

#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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM