0

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
Altern8
  • 1
  • 1

1 Answers1

1

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);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621