My cin is being ignored inside a while loop

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 08:12:52
#include <iostream>
#include <limits>

int main()
{
    int lives = 0;
    std::cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << std::endl;


    while(!(std::cin >> lives) || lives < 1 || lives > 3)
    {
        std::cout << "You need to input a number, not words." << std::endl;
        std::cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << std::endl;
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

    return 0;
}

Alright. std::cin.clear(); takes care of resetting the fail bits. std::cin.ignore removes any wrong input left in the stream. And I've adjusted the stop condition. (isDigit was a redundant check, if lives is between 1 and 3 then clearly it's a digit).

When std::istream can't read a value, it goes into failure mode, i.e., std::failbit is set and the stream yields false when tested. You always want to test if a read operation was successful:

if (std::cin >> value) {
    ...
}

To restore the stream to good state you'd use std::cin.clear() and you probably need to ignore bad characters, e.g., using std::cin.ignore().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!