0

它适用于任何数字输入,但如果您输入一个字母或单词,它会永远循环错误消息。如何解决这个问题?

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

1 回答 1

2

那是因为提取失败std::cin operator>>

failbit未提取字符或提取的字符无法解释为适当类型的有效值时设置

因此,在您的情况下,您可以通过以下方式解决:

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

工作现场示例

于 2013-08-29T19:41:36.080 回答