输入字符时无限循环 [英] Infinite Loop when a character is entered

查看:102
本文介绍了输入字符时无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图限制用户仅输入"1"或"2".

I am trying to restrict the user to enter only '1' or '2'.

int ch;

do
{
    cout<<"Enter: \n";
    cin>>ch;
    switch(ch)
    {
    case 1:
        cout<<"1";
        break;
    case 2:
        cout<<"2";
        break;
    default:
        cout<<"Retry\n";
    }
}while(ch != 1 && ch != 2);

当我输入1或2以外的任何数字时,程序会要求用户重试以正常运行,但是当我输入字符时,程序将进入重试"和输入"的无限循环.

When I enter any number other than 1 or 2, the program runs fine by asking user to retry, however when I enter a character, the program enters into an infinite loop of 'Retry' and 'Enter'.

推荐答案

这是因为当您输入非数字字符时,输入运算符无法将其解析为整数,并将该字符保留在缓冲区中.因此,循环的下一次迭代将再次读取完全相同的字符.一次又一次,依此类推.

That's because when you enter a non-digit character then the input operator can't parse that as an integer, and it leaves the character in the buffer. So next iteration of the loop it reads the exact same character again. And again and again and so on.

解决此问题的最简单方法是简单地要求流忽略该行的其余部分:

The simplest way to overcome this problem is to simply ask the stream to ignore the rest of the line:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip bad input

还有其他方法,例如将整行读取为一个字符串,将该字符串放入输入字符串流中,然后从该流中读取整数.不过,还有更多工作要做.这样确实意味着您不必检查std::cin上的输入失败,尽管您必须使用上述方法进行此操作.

There are other ways as well, like reading the whole line into a string, put that string into an input string stream, and read the integer from that stream instead. A little more work though. This way does mean you don't have to check for input failure on std::cin though which you must do with the above method.

您完成的代码可能类似于

You complete code could look something like

int n;
do
{
    if (!std::cin >> n)
    {
        std::cout << "Only numbers accepted. Please try again.\n";
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // Skip bad input
        std::cin.clear();  // Clear error flags
    }

    // switch ...
} while (...);

这篇关于输入字符时无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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