简体   繁体   English

C ++输入一个char而不是int导致无限循环。 如何检查输入错误?

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

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'. 然后,当用户输入错误的数据(例如字符“ a”或“ b”)时。 The program will go into an infinite loop. 程序将进入无限循环。

How to catch the wrong cin? 如何捕捉错误的cin? How to clear the buffer and give user the chance to input a right data again? 如何清除缓冲区并为用户提供再次输入正确数据的机会?

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. 清除cin状态并忽略错误的输入。

for(i=0; i<n; i++)
{
    while (!(cin>>a[i])) {
        cin.clear();
        cin.ignore(256,'\n');
        cout << "Bad Input, Please re-enter";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM