【问题标题】:How to terminate cin>> input with specific word/letter/number/etc如何使用特定的单词/字母/数字/等终止 cin>> 输入
【发布时间】:2014-05-24 00:30:47
【问题描述】:

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

练习是这样的:用姓名和年龄填充 2 个向量(1 个字符串和 1 个整数), 通过“不再”行终止输入,询问程序需要输出相应年龄的名称(或“未找到名称”)。我的问题是 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");

}

【问题讨论】:

    标签: c++ string io inputstream formatted-input


    【解决方案1】:

    "以"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

    【讨论】:

    • 我知道我需要指出这一点:请不要使用高级的东西,我正在写一本 Bjarne Stoustrup c++​​ 的书,到目前为止我学习了函数、循环和向量。所以 getline .empty() istringstream is() 对我来说是 SF。我可以使用它,但如果您知道我的意思,我就不明白这一点。谢谢
    • @user3446166:如果你在std::cin 上使用&gt;&gt;,那么std::getline 读取整个字符串是完全合理的选择。代替line.empty() 你可以用line == "" 代替istringstream 你可以手动解析这一行。
    • 在练习中它是这样的(我引用):“按行终止输入不再(“更多”将使读取另一个整数的尝试失败)。“即使我使用 getline 它不是我要求做的(我认为)。
    • 我可以使用字符串输入姓名和年龄并使用 if(condition) break 进行检查吗? ?
    • 显然你是对的,而 (cin>>name>>age && name!="NoName") 是解决方案
    猜你喜欢
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多