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

六月ゝ 毕业季﹏ 提交于 2019-12-06 14:13:06

问题


One part of my program: Let user input a series of integer, and then put them into an array.

int n=0;
cout<<"Input the number of data:";
cin>>n;
cout<<"Input the series of data:";
int a[50];
for(i=0; i<n; i++)
{
    cin>>a[i];

}

Then, when user input wrong data such as a character 'a' or 'b'. The program will go into an infinite loop.

How to catch the wrong cin? How to clear the buffer and give user the chance to input a right data again?


回答1:


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;



回答2:


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


来源:https://stackoverflow.com/questions/22193550/c-input-a-char-instead-of-int-lead-to-endless-loop-how-to-check-the-wrong-inp

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