当前位置: 动力学知识库 > 问答 > 编程问答 >

c - 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

网友答案:

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);
分享给朋友:
您可能感兴趣的文章:
随机阅读: