3

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();
Satyam Singh
  • 33
  • 1
  • 6

2 Answers2

1

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

0

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

MikeCAT
  • 61,086
  • 10
  • 41
  • 58
  • 1
    Thanks alot. Works like a charm. But can you please explain me why did I had to enter cin.ignore(); twice? I couldn't get the explaination you have written above... – Satyam Singh May 15 '16 at 03:38
  • @SatyamSingh Related: [c++ - Why does std::getline() skip input after a formatted extraction? - Stack Overflow](http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – MikeCAT May 15 '16 at 03:41