1

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

}

4

1 回答 1

2

“按行终止输入"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

于 2014-04-10T10:54:05.903 回答