简体   繁体   English

为什么C ++中的“按Enter继续”代码不起作用?

[英]Why is this “Press Enter to Continue” code in C++ not working?

So, I was making a simple quiz program for kids in C++ (I am really a beginner to programming). 所以,我正在为C ++中的孩子们制作一个简单的测验程序(我真的是编程的初学者)。 What I wanted to do was require the user to press Enter after the first question and only upon pressing enter, the second question is visible. 我想要做的是要求用户在第一个问题后按Enter键,只有按回车键,才能看到第二个问题。 But due to some reasons, C++ doesn't waits for the user to enter an output in the cin statement and automatically prints the next question. 但由于某些原因,C ++不会等待用户在cin语句中输入输出并自动打印下一个问题。

Here's the code: 这是代码:

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();

Most probably you have entered Enter after ans/input (with one word). 很可能你在ans / input之后输入了Enter (只有一个单词)。 So, when you press Enter , it takes ans string as input and treats the following newline as delimeter. 因此,当您按Enter键时 ,它将ans字符串作为输入,并将以下换行视为分隔符。 As a result, newline is not read and it remains in the input buffer which is automatically taken as next input. 因此,不会读取换行符并将其保留在输入缓冲区中,该缓冲区将自动作为下一个输入。 That is, cin.ignore() ignore this newline and control goes to the next instructions. 也就是说, cin.ignore()忽略这个换行符,控制转到下一条指令。

To fix it, use cin.getline(ans) / getline(cin, ans) instead of cin or use another cin.ignore() to ignore your next Enter ("Press Enter to Continue"). 要修复它,请使用cin.getline(ans) / getline(cin,ans)代替cin或使用另一个cin.ignore()忽略下一个Enter (“按Enter继续”)。

You may have already entered "enter" after providing some data for ans . 在为ans提供一些数据后,您可能已经输入了“enter”。 In that case, the cin.ignore() will read the "enter" and immediately return. 在这种情况下, cin.ignore()将读取“enter”并立即返回。 Therefore, you would want another cin.ignore() for wait for another "enter". 因此,您需要另一个cin.ignore()来等待另一个“enter”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM