Pergunta

How to use cin>> again after it fails or how to exit while(cin>>some_string>>some_int) legitimately so that cin>> can be used again?

Exercise goes something like this : Fill 2 vectors (1 string and 1 int) with name and age, terminate input by the line "no more", ask for a name for which the program need to output corresponding age ( or "name not found"). My problem is with cin>> : when i enter "no more" any attept of using cin>> again is fail.

code:

{
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");

}

Foi útil?

Solução

"terminate input by the line "no more""

Yould could read the input by lines, not by words:

#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 */ }
}

If you want to take care of situation when there are additional characters after this no more then you might use line.substr(0,7) != "no more" and if you just want to find out if no more is within the line, not necessarily at the beginning, you can do: line.find("no more") != std::string::npos

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top