首页 文章

当询问用户2个号码时,无限循环发生

提问于
浏览
0

我正在尝试实现一个简单的游戏,其中要求用户提供0到10之间的2个有效整数坐标 . (int row,int column)

我意识到的一个例子是:

插入坐标:4C
*错误,行数和列数必须是整数

插入坐标:44 2
*错误,行数或列数太高

插入坐标:4 3
您输入的坐标为(4,3)

我通过do-while循环实现了所有这些 .

int r,c;
do{
cout<<"Insert coordinates: ";
cin>>r>>c;
    if (cin.fail())
{
    cout << "ERROR: Number of row and column must be integer." << endl << endl;

}
    if ((r<0 || r>10) || (c<0 || c>10)
{
    cout << "*Error, number of row or column are too high [0-10]" << endl << endl;

}
 cout<<endl;
}
while (((r<0 || r>10)||(c<0 || c>10)) || cin.fail());

此代码无法正常运行 . 如果我在0到10之间输入2个数字,它就可以了 . 如果我输入一个大于10的数字,它也可以 . 但是,如果我输入一个字符,程序将进入无限循环,并且无法正常工作 .

如何实现这个来处理字符输入错误?如果用户输入一个角色,有没有办法识别并保持在while循环中?

4 回答

  • 0

    如果输入字母而不是数字,则不会从输入缓冲区中提取该字母,因此您的代码将永远失败 .

    如果输入失败(为什么不使用例如 if (!(cin >> r >> c)) ?),那么你可以通过调用ignore函数来跳过该行:

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

    您还要清除 failbit ,因为它没有自动清除,这是通过clear功能完成的 .


    您还可以通过获取整行并使用std::istringstream进行解析来绕过此问题:

    do
    {
        std::string line;
        if (!std::getline(std::cin, line))
            ... // Could not read from input
    
        std::istringstream iss(line);
        int r, c;
        if (!(iss >> r >> c))
            ... // Failed to parse as numbers
    
        ...
    
    } while (...);
    
  • 0

    您只需检查是否输入了字符,例如:

    if (x >= 0x41 && x <= 0x7A)
    cout<<"error, you entered a letter";
    
  • 1
    (((r<0 || r>10)||(c<0 || c>10)) || cin.fail());
    

    改成

    (((r>0) && (r<10))||((c>0) && (c<10)))     //It will work, no need to check cin.fail();
    

    如果cin失败,那么它可能会在缓冲区中产生错误,所以最好退出程序 .

  • 0

    程序进入无限循环,因为您永远不会清除失败状态 . 您可以简化entire loop

    #include <iostream>
    using namespace std;
    
    int main() 
    {
        int r = -1;
        int c = -1;
        bool valid = false;
        do
        {
            cout<<"Insert coordinates: ";
            if (cin >> r >> c)
            {
                if (r >= 0 && r <= 10 && c >= 0 && c <= 10)
                {
                    valid = true;
                }
            }
            else
            {
                cin.clear();
                cin.ignore();
            }
    
            if (!valid)
            {
                cout << "ERROR:  Number of row and column must be an integer between 0 and 10." << endl;
            }
        } while (!valid);
    
        cout << "You entered (" << r << ", " << c << ")" << endl; 
    
        return 0;
    }
    

相关问题