Satyam Singh
Satyam Singh

Reputation: 33

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

Upvotes: 3

Views: 4930

Answers (2)

Md. Monirul Islam
Md. Monirul Islam

Reputation: 731

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

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

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

Upvotes: 2

Related Questions