为什么 C++ 中的 "Press Enter to Continue" 代码不起作用?

Why is this "Press Enter to Continue" code in C++ not working?

所以,我正在用 C++ 为孩子们制作一个简单的测验程序(我真的是编程的初学者)。我想做的是要求用户在第一个问题后按 Enter,只有在按 enter 后,第二个问题才可见。但由于某些原因,C++并没有等待用户在cin语句中输入一个输出,而是自动打印下一题。

代码如下:

cout << "Q1. Which of these languages is not used to make Computer Software?" << endl;
cout << "a. Python" << endl;
cout << "b. Java" << endl;
cout << "c. C++" << endl;
cout << "d. HTML" << endl;
cout << "" << endl;
cin >> ans;
cout << "" << endl;
cout << "Press Enter to Continue";
cin.ignore();

在为 ans 提供了一些数据后,您可能已经输入了 "enter"。在这种情况下,cin.ignore() 将读取 "enter" 并立即读取 return。因此,您需要另一个 cin.ignore() 来等待另一个 "enter".

很可能您在 ans/input 之后输入了 Enter(一个字)。因此,当您按 Enter 时,它会将 ans 字符串作为输入并将以下换行符视为分隔符。 因此,换行符不会被读取,它会保留在输入缓冲区中,自动作为下一个输入。也就是说,cin.ignore() 忽略此换行符并控制转到下一条指令。

要修复它,请使用 cin.getline(ans)/getline(cin, ans) 而不是 cin 或使用另一个 cin.ignore() 忽略你的下一个 Enter ("Press Enter to Continue") .