This function is suppose to go back 1 step in the connect 4 game, however, it goes back twice... I went through the function with a debugger, and it seems to skip the getc() call I don't know why. Any help is much appreciated!
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;
}
}
The logic used in
while((input != 'q' || input != 'Q') && temp != NULL){
is faulty. You need to use:
while((input != 'q' && input != 'Q') && temp != NULL){
Your condition for input
in the while
condition is wrong. One of the two terms will be true, regardless of the value of input
, so the loop only terminates here if temp != NULL
.
But you actually break
on user input later in the loop using a correct expression, so there is actually no need to test in the loop condition. Instead, use only temp
here:
while ( temp != NULL ) {
Now you can also change
char input = 'q';
to
char input;
because it is now not before user input is read in the loop.
Note that getc
returns an int
, not a char
to provide EOF
, you also should test for. (thanks to @chux for pointing me at this).
As you just use it inside the loop, you can move it, to (all changes included):
while ( temp != NULL ) {
int input;
...
if ( input == EOF || input == 'q' || input == 'Q' )
break;
temp = temp->next;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.