与fgets();这是如何在这部分代码中工作的? C编程

时间:2015-01-07 23:44:01

标签: c fgets

我使用教程写了一个Tic Tac Toe游戏。现在我只是通过代码看看我不理解的东西,我想出了这个部分,女巫让我感到困惑。

 char userInput[4];

int moveOk = 0;
int move = -1;

while(moveOk == 0)
{
    printf("Enter a number from 1 - 9: ");
    fgets(userInput, 3, stdin);
    fflush(stdin);
    printf("\n\n");
*The code continues, but the rest of it is not important*

这部分如何运作?我甚至不知道如何提出这个问题。 抱歉。那么fgets()中的三个值是什么;以及他们如何互相互动?

fgets(userInput, 3, stdin);
    fflush(stdin);

1 个答案:

答案 0 :(得分:3)

来自fgets手册

char *fgets(char *s, int size, FILE *stream);
  

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

所以fgets()从输入流中获取最多2个字符,或直到按下返回键(发送'\n'个字符)或{{1}发送,并将结果存储在EOF

然后,您可以尝试使用userInput将两个字符串转换为数字。