2

每次我运行以下代码并输入 1 或 0 时,以下代码都包含一个逻辑错误,while 循环中的代码仍会执行。有人能告诉我为什么吗?

bool getmove()
{
    bool move;
    cout << "Would you like to make the first move?(1 for yes 0 for no)\n";
    cin >> move;
    while(move != 1 || move != 0 || !cin.good())
    {
        if(!cin.good())
        {
            cout << "ERROR please try again\n";
            cin.clear();
            cin.ignore(80,'\n');
            cin >> move;
        }
        else
        {
            cout << "Invalid input please try again\n";
            cin >> move;
        }
    }
    return move;
}
4

2 回答 2

1

看看这一行:

while(move != 1 || move != 0 || !cin.good())

情况总是如此move != 1 || move != 0(因为不能两者兼而有之)。

此外,您可以通过读取字符串之类的内容并对其进行测试来避免一些麻烦,而不是依赖于强制转换。

于 2012-10-23T02:41:51.157 回答
1

如果您尝试编写一个可以验证布尔值输入的函数,您的代码可以简化为:

bool getmove()
{
    bool move;
    cout << "Would you like to make the first move?(1 for yes 0 for no)\n";
    while (!(cin >> move))
    {
        cout << "Invalid input please try again\n";
        cin.clear();
        cin.ignore(80, '\n');
    }
    return move;
}

重要的是要意识到这while (!(cin >> move))将重复循环,直到可以从控制台读取有效的布尔值并将其写入move.

于 2012-10-23T03:02:04.863 回答