user2684874
user2684874

Reputation:

Why does this while loop forever when given a string?

It works fine with any number input, but if you enter a letter or a word it loops the error message forever. How would one go about solving this?

while(choice != 2){
    cout << "Player stats:\n Level ------ " << level << "\n Health ----- " << health << "\n Attack ----- " << attack << "\n Experience - " << exp << endl;
    cout << " " << endl;
    cout << "-Choose an option-" << endl;
    cout << "1| Fight | Fight a monster | Monsters are based on your level" << endl;
    cout << "2| Exit  | Exit the game" << endl;

    currentHealth = health;

    cin.clear();

    cin >> choice;

    while(choice < 1 || choice > 2){
        cout << "Invalid choice! Try again!" << endl;
        cin >> choice;
    }

Upvotes: 0

Views: 190

Answers (1)

Pierre Fourgeaud
Pierre Fourgeaud

Reputation: 14510

It is because the extraction of std::cin operator>> fail.

The failbitis set when either no characters were extracted, or the characters extracted could not be interpreted as a valid value of the appropriate type.

So in your case, you can solve it by :

while(choice != 2){
    cout << "Player stats:\n Level ------ " << level << "\n Health ----- " << health << "\n Attack ----- " << attack << "\n Experience - " << exp << endl;
    cout << " " << endl;
    cout << "-Choose an option-" << endl;
    cout << "1| Fight | Fight a monster | Monsters are based on your level" << endl;
    cout << "2| Exit  | Exit the game" << endl;

    currentHealth = health;

    // FIX BEGIN HERE
    // The do-while loop and the conditions are just examples
    // cin.clear() and cin.ignore() are important

    do
    {
        if ( cin >> choice && ( choice >= 1 || choice <= 2 ) )
        {
            break;
        }
        else
        {
            cout << "Invalid choice! Try again!" << endl;
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
    } while(1);
}

Working live example.

Upvotes: 1

Related Questions