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

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

本文关键字:获取 CIN getline cin string      更新时间:2023-10-16

下面的代码仅在第一个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输入程序。

这使得输入仍在输入缓冲区中等待。在循环的下一次迭代中,std::getline查看输入缓冲区,查看输入,并将其读取为空行。由于它看到已输入的"行",因此它不会等待更多 - 它只是在该空行中读取,并将其返回到您的程序进行处理。

避免

这种情况的常用方法是避免混合使用面向字符的输入和面向行的输入。如果无法完全避免,则通常需要添加代码以忽略面向字符的输入和面向行的输入之间的输入行的其余部分。