当使用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
输入程序。
这使得输入仍在输入缓冲区中等待。在循环的下一次迭代中,std::getline
查看输入缓冲区,查看输入,并将其读取为空行。由于它看到已输入的"行",因此它不会等待更多 - 它只是在该空行中读取,并将其返回到您的程序进行处理。
这种情况的常用方法是避免混合使用面向字符的输入和面向行的输入。如果无法完全避免,则通常需要添加代码以忽略面向字符的输入和面向行的输入之间的输入行的其余部分。
相关文章:
- std::cin 从控制台获取两种不同的变量类型,'storing'以后使用第二种类型?
- 从 cin 获取 c++ 中结构中多个枚举的输入
- 如何使 std::istream 从键盘获取输入(如 std::cin)?
- 当我们声明 cin 为 int 并从 cin 中获取输入并在 cout 中打印 cin 时会发生什么?
- 有没有办法将 getline() 与外部文本文件一起使用,然后重新获得 cin 的控制权以从控制台获取输入?
- 从 R 控制台获取用户输入:Rcpp 和 std::cin
- 如何将字符输入限制为仅获取一个字符串"cin"
- 如何使用CIN将输入整数值获取到char类型变量中
- 填充字符数组的最佳方法(获取与cin.getline)
- 无法获取哨兵值以读取多个 CIN 输入?
- 如何阻止 cin.getline() 导致控制台在找不到分隔符时重复获取用户输入?
- C++:获取用户通过cin输入的数据类型
- 我在使用 cin.getline() 从用户那里获取 3 个字符串并使用指针数组来存储它们时遇到问题
- 使用C - CIN获取几个整数数字,然后将它们放入数组中
- 获取线跳到下一个 cin 并跳过上一个 cin
- 获取热线(CIN,答案5);在我的程序结束时不起作用
- C++使用cin.get来获取一个字符,但在遇到EOF时不会结束while循环
- C++获取线和CIN阅读
- 通过用户获取 cin 来命名输出文件
- 使用 cin.get 获取一个整数