函数中的Cout在C ++中打印次数过多

时间:2017-10-14 08:20:43

标签: c++ cin

我正在尝试使用C ++制作基本游戏,以扩展我对语言的理解。我有以下代码,当用户输入无效答案时,他们会被要求再试一次。

void turn_update()
{
    player = (player % 2 == 0)? 1 : 2;
    mark = (player == 1)? 'X' : 'O';

    cout << " Please make your move, " << mark << ":" << endl;
    int x = 0;
    while(!(cin >> x) || x > 9 || x < 1 || board[x] == 'X' || board[x] == 'O')
    {
        cin.clear();
        cin.ignore();
        cout << " Invalid input. Try again: ";
    }
    cout << "\n" << endl;
    board[x] = mark;
    draw_board(board);
}

当用户输入说“123456”时,响应将为:

 Please make your move, X:
 123456
 Invalid input. Try again:

现在这就是我想要的,一封信也是如此。 E.g:

 Please make your move, X:
 a
 Invalid input. Try again:

但是当用户输入两个或更多字母时,Invalid input: Try again:将打印出与输入字母数相同的次数...

 Please make your move, X:
 aa
 Invalid input. Try again:  Invalid input. Try again:

 Please make your move, X:
 aaa
 Invalid input. Try again:  Invalid input. Try again:  Invalid input. Try again:

有人可以解释一下原因吗?我没有很多使用C ++的经验,如果您对常规代码有任何提示,我将非常感谢您的建议。

2 个答案:

答案 0 :(得分:0)

在while循环中仅使用cin.clear()。

while (!(cin >> x) || x > 9 || x < 1 || board[x] == 'X' || board[x] == 'O'))
{
    cin.clear();
    cout << " Invalid input. Try again: ";
}

答案 1 :(得分:0)

cout << " Please make your move, " << mark << ":" << endl;
int x = 0;

while (true)
    while (!(cin >> x)) {
        cin.clear();
        cin.ignore();
        cout << "Please provide a valid number in range 1 - 9. Try again: ";
    }
    if (x < 1 || x > 9) {
        cout << "value out of range 1 - 9"
        continue;
    }
    if (board[x] != 'X' && board[x] != 'O') {
        break;
    }
    cout << "Cant make a move at " << x << " occupied by: " << board[x];
}