C ++输入一个char而不是int导致无限循环。如何检查错误的输入? [英] C++ Input a char instead of int lead to endless loop. How to check the wrong input?

查看:200
本文介绍了C ++输入一个char而不是int导致无限循环。如何检查错误的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序的一部分:让用户输入一系列整数,然后将它们放入数组。

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];

}

然后,当用户输入错误的数据, a'或'b'。该程序将进入无限循环。

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

如何捕获错误的cin?如何清除缓冲区并让用户有机会再次输入正确的数据?

How to catch the wrong 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;

这篇关于C ++输入一个char而不是int导致无限循环。如何检查错误的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆