0

我正在尝试实现一个简单的游戏,要求用户输入 0 到 10 之间的 2 个有效整数坐标。(int 行,int 列)

我会意识到的一个例子是:

插入坐标: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

4 回答 4

1

If you enter a letter instead of a number, then that letter is not extracted from the input buffer, so your code will continue to fail forever.

If the input fails (why not use e.g. if (!(cin >> r >> c))?) then you can skip the line by doing calling the ignore function:

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

You also want to clear the failbit as it's not cleared automatically, this is done with the clear function.


You can also bypass this problem by getting the whole line, and using std::istringstream for the parsing:

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 (...);
于 2013-11-13T14:50:54.237 回答
0

程序进入无限循环,因为您从未清除失败状态。您可以简化整个循环

#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;
}
于 2013-11-13T15:19:43.237 回答
0
(((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 失败,那么它可能会在缓冲区中产生错误,所以最好退出程序..

于 2013-11-13T14:54:42.290 回答
0

您可以简单地检查是否输入了字符,例如:

if (x >= 0x41 && x <= 0x7A)
cout<<"error, you entered a letter";
于 2013-11-13T14:54:45.620 回答