while loop to infinity when the input of a cin is a 'dot'

后端 未结 4 2074
执念已碎
执念已碎 2021-01-27 19:22

I am having trouble using the cin method to acquire a variable. When the input is a number there is no problem, but when it is a special character like a dot [.], the whileloop

4条回答
  •  梦谈多话
    2021-01-27 19:53

    The other solution besides the one accepted is to clear the cin's failbit and ignore the last input like below:

    cout << "What is your race" <> *race;
    while(*race<1||*race>3)
    {
        // Clears the state of cin to be in good state
        cin.clear();
        // Ignores the last input read so that it's not read back again
        cin.ignore();
        system("cls");
        cout << "Wrong choice"<> *race;
    }
    

提交回复
热议问题