Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading