当使用getline(cin,string)时,cin会自动获取其值而不会询问

时间:2015-03-10 04:50:35

标签: c++ cin getline

以下代码仅在第一个while循环中不能正常工作,它会自动将值赋给cin,所以我没有机会在下一个循环之前给它一个输入。为什么会这样?

char again = 'y';
while (again=='y') { 
  int n=1 , chance = 5, score = 0, level = 1;
  if (n == 1) {
    cout << "Game begin!"<<endl;
  while (chance) {
    cout << "You have " << chance << " chances left." << endl;
    cout<<"level "<<level<<" question!"<<endl;
    vector<string> actorset = game(graph,level);
    int correct = 0;
    string s;
    cout << "\nyour answer is:";
    std::getline(cin, s);
    cout << "Your Answer is " << s <<endl;
    vector<string>::iterator vit = actorset.begin();
    vector<string>::iterator ven = actorset.end();
    cout << "Correct Answers are: "<<endl;
    for ( ; vit != ven; vit++) {
      if (s.compare(*vit) == 0) {
        correct = 1;
      }
      cout << *vit <<'\t'; 
    }
    cout <<'\n';
    if (correct == 0) {
    chance --;
    cout << "Incorrect answer" << endl;
    cout << "Your total score is " << score <<"."<<endl;
    } else {
    score += 10;
    level++;
    cout <<"Correct answer! You get 10 points!"<<endl; 
    cout << "Your total score is " << score <<"."<<endl;
    }
  }
}
cout <<"high score handler"<<endl;
output.open (outfile_name, std::fstream::in | std::fstream::out);
highscore(output,score);
cout << "type y for another try: ";
cin >> again;
}

1 个答案:

答案 0 :(得分:2)

罪魁祸首几乎肯定是你cin >> again;

至少在大多数系统上,您需要按 y Enter 之类的内容,在程序中输入y

使输入仍然在输入缓冲区中等待。在循环的下一次迭代中,std::getline查看输入缓冲区,看到输入,并将其作为空行读取。因为它看到了&#34;线&#34;已输入,它不会等待更多 - 它只是读取该空行,并将其返回到您的程序进行处理。

避免这种情况的通常方法是避免混合面向字符的输入和面向行的输入。如果你无法完全避免它,那么你通常想要添加代码来忽略面向字符的输入和面向行的输入之间的输入行的其余部分。