当使用 getline(cin, string) 时,cin 会自动获取它的值而无需询问

when use getline(cin, string), cin automatically take its value without ask

以下代码仅在第一个 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;
}

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

至少在大多数系统上,你需要按yEnter之类的东西才能将y输入到程序中.

这使得 enter 仍在输入缓冲区中等待。在循环的下一次迭代中,std::getline 查看输入缓冲区,看到 enter,并将其作为空行读取。因为它看到一个 "line" 已经被输入,它不会等待更多——它只是读入那个空行,然后 returns 它到你的程序进行处理。

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