简体   繁体   中英

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;
    }

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

The failbit is 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM