Search code examples
c++while-loopbooleancin

Making the user give a boolean input with while loop


I have just started learning C++ and trying to learn the syntax.

#include <iostream>
#include <limits>
using namespace std;
int main(){
    bool answer;
    cout << "Did you enjoy testing this program? (1 for yes, 0 for no) ";
    cin >> answer;
    while (!(cin >> answer)) {
        cout << "Invalid value!\n";
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Please type either 0 or 1: ";
        cin >> answer;
    }
    cout << "Your feedback has been registered. Feedback: " << answer;
}

The aim is to keep making the user ask over and over until they input either 0 or 1. The code snippet just makes things freeze when either of those values is given. How should this be fixed?


Solution

  • The cin >> answer; statement above the loop, and the cin >> answer; statement at the end of the loop body, both need to be removed.

    You are prompting the user to enter a value, then you read in that value and ignore it, and then you wait for the user to enter in another value, even though you didn't prompt the user to enter more than 1 value.

    If they do happen to enter a 2nd value, and it fails, your loop will then prompt the user to enter in a new value, then you read in that value and ignore it, and then you wait for the user to enter yet another value without prompting the user to do so.

    You should be invoking cin >> answer only 1 time per loop iteration, eg:

    #include <iostream>
    #include <limits>
    using namespace std;
    
    int main(){
        bool answer;
        cout << "Did you enjoy testing this program? (1 for yes, 0 for no) ";
        // cin >> answer; // <- remove this!
        while (!(cin >> answer)) {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Invalid value!\n";
            cout << "Please type either 0 or 1: ";
            // cin >> answer; // <- remove this!
        }
        cout << "Your feedback has been registered. Feedback: " << answer;
    }