【问题标题】:C++ Input a char instead of int lead to endless loop. How to check the wrong input?C++ 输入一个 char 而不是 int 会导致无限循环。如何检查错误的输入?
【发布时间】:2014-03-05 09:26:55
【问题描述】:

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

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'。程序将进入无限循环。

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

【问题讨论】:

  • 请记住,输入(和输出)流可以在 boolean expressions 中使用,就像在 if 语句中一样。

标签: c++ infinite-loop cin


【解决方案1】:

只需先检查输入是否为数字,然后将其附加到数组中

    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;

【讨论】:

  • @YingliYan 接受答案,以便其他人知道此解决方案有效:)
【解决方案2】:

清除cin状态并忽略错误输入。

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

【讨论】:

    猜你喜欢
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    • 2012-07-04
    相关资源
    最近更新 更多