简体   繁体   中英

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). 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. 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.

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). So, when you press Enter , it takes ans string as input and treats the following newline as delimeter. 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.

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").

You may have already entered "enter" after providing some data for ans . In that case, the cin.ignore() will read the "enter" and immediately return. Therefore, you would want another cin.ignore() for wait for another "enter".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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