Altern8 Altern8 - 3 months ago 28
C Question

fgets or strtok error returning unwanted third line

I had the following code to try and get 2 values for 2 different players, however this code is causing an unwanted third line to appear as shown below.

for(int i = 0; i < 6; i++){
printf("Player %c>", player);
fgets(move, 4, stdin);
y_coord = strtok(move, sp);
x_coord = strtok(NULL, sp);


printf("You entered: %s, %s\n", x_coord, y_coord);
if(player == 'O'){
player = 'X';
}
else{
player = 'O';
}
}


output:

Player O>5 5
You entered: 5, 5
Player X>You entered: (null),

Player O>^C

Answer

The problem is that you read only three characters, which leaves the newline in the input buffer.

The size passed to fgets must include the terminating '\0' character, so to have fgets read the newline as well you need a buffer size of 5 character, i.e.

char move[5];  // Two characters separated by space, plus newline and terminator
...
fgets(move, sizeof(move), stdin);