为什么这个在给定字符串时永远循环?

时间:2013-08-29 19:28:31

标签: c++ string while-loop

任何数字输入都可以正常工作,但是如果输入一个字母或一个单词,它会永远循环错误信息。如何解决这个问题?

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

1 个答案:

答案 0 :(得分:2)

这是因为提取std::cin operator>> fail

当未提取任何字符时设置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);
}

Working live example