C++ Input a char instead of int lead to endless loop. How to check the wrong input?

荒凉一梦 提交于 2019-12-04 19:31:00

Simply check if the input is a number first and then append it to the array

    int x;
    std::cin >> x;
    while(std::cin.fail())
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        std::cout << "Bad entry.  Enter a NUMBER: ";
        std::cin >> x;
    }

    a[i] = x;

Clear the cin state and ignore bad input.

for(i=0; i<n; i++)
{
    while (!(cin>>a[i])) {
        cin.clear();
        cin.ignore(256,'\n');
        cout << "Bad Input, Please re-enter";
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!