wvm2008
wvm2008

Reputation: 3034

using cin.ignore()? Not sure how to make it work

bool showMenu(romanType roman){
    cout << endl;
    cout << "Just enter a number to choose an option" << endl;
    cout << "1: Print the Roman Numeral" << endl;
    cout << "2: Print the decimal value" << endl;
    cout << "3: Enter a new Roman Numeral" << endl;
    cout << "4: Quit the program" << endl;
    cout << endl;
    while (true) {

        cout << "Your choice:" << endl;
        int input;
        cin >> input;
        if (input == 1) {
            cout << roman.getRomanString() << endl;
        } else if(input ==2) {
            cout << roman.getDecimalValue() << endl;
        } else if(input == 3) {
            return true;
        } else if(input == 4) {
            return false;
        } else {
            cout << "Invalid selection, please make a valid selection." << endl;
        }
    }
}

Alight, so by and large this works fine, I'm just having one small problem with my final else statement. As long as the user has entered a type of int, the loop does what it is supposed to, however if any kind of string is entered (i.e. 45r, rts, 3e5) the loop stops taking user input and just spirals infinitely, cout(ing) Invalid selection... and Your choice... over and over again. I think I need to use .ignore() to drop the \n in the case of a string, but I'm not sure of how to do that. Am I on the right track?

Upvotes: 1

Views: 4924

Answers (1)

Zeta
Zeta

Reputation: 105985

Yes, you're on the right track.

cin >> input tries to extract an integer. If this fails no symbols are extracted from cin and the failbit is set. In this case the extraction won't work anymore. You have to ignore the rest of the user input and clear the error bits:

} else {
    cout << "Invalid selection, please make a valid selection." << endl;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(),'\n');

// numeric_limits<streamsize>::max() returns the maximum size a stream can have,
// see also http://www.cplusplus.com/reference/std/limits/numeric_limits/
}

See also Why is this cin reading jammed?.

Upvotes: 4

Related Questions