C - 为什么这个 运行 循环两次?

C - Why does this loop run through twice?

这个函数应该在 connect 4 游戏中返回 1 步,然而,它返回了两次......我用调试器检查了这个函数,它似乎跳过了我不喜欢的 getc() 调用不知道为什么。非常感谢任何帮助!

char UndoBoard(char x[ROWS][COLS], char * player){
    struct Node* temp = head;
    int i,j;
    temp = temp->next;
    char input = 'q';
    while((input != 'q' || input != 'Q') && temp != NULL){
        for (i=0;i<ROWS;i++){
            for (j=0;j<COLS;j++){
            x[i][j] = temp->data[i][j];
            }
        }
        printBoard(x);
        if(*player == 'O')*player = 'X';
        else *player = 'O';
        printf("b - undo one step more, f - go forward, q - resume game from here\n");
        input = getc(stdin);
        if(input == 'q' || input == 'Q')break;
        temp = temp -> next;
    }
}

中使用的逻辑
while((input != 'q' || input != 'Q') && temp != NULL){

有问题。您需要使用:

while((input != 'q' && input != 'Q') && temp != NULL){

您在 while 条件中 input 的条件是错误的。无论 input 的值如何,这两项中的一项将为真,因此循环仅在 temp != NULL.

时在此终止

但是您实际上 break 稍后在循环中对用户输入使用了正确的表达式,因此实际上没有必要在循环条件中进行测试。相反,在此处仅使用 temp

while ( temp != NULL ) {

现在你也可以改变

char input = 'q';

char input;

因为现在不是在循环中读取用户输入之前。

注意getcreturns一个int,不是一个char提供EOF,你也应该测试一下。 (感谢@chux 指点我)。

因为你只是在循环中使用它,你可以将它移动到(包括所有更改):

while ( temp != NULL ) {
    int input;

    ...

    if ( input == EOF || input == 'q' || input == 'Q' )
        break;

    temp = temp->next;
}