fgets();这在代码的这一部分中是如何工作的?C程序设计

fgets();这在代码的这一部分中是如何工作的?C程序设计,c,fgets,C,Fgets,我用教程写了一个井字游戏。现在我正在仔细检查代码,看看我不明白什么,我想出了这个部分,巫婆把我弄糊涂了 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

我用教程写了一个井字游戏。现在我正在仔细检查代码,看看我不明白什么,我想出了这个部分,巫婆把我弄糊涂了

 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);

fgets
手册

char *fgets(char *s, int size, FILE *stream);
fgets()从流中最多读入一个小于大小的字符,并将它们存储到s指向的缓冲区中。EOF或换行符后,读取停止。如果新行被读取,它将被存储到缓冲区中。在缓冲区中最后一个字符之后存储一个终止的空字节('\0')。

因此,
fgets()
,从输入流中最多提取2个字符,或者直到按下返回键(发送
'\n'
字符)或发送
EOF
,并将结果存储在
userInput


然后,您可以尝试使用
strtol

将两个字符串转换为一个数字。您应该删除
fflush(stdin)
,因为它是未定义的行为,
fflush()
用于输出流。您阅读过
fgets
的文档吗?至于
fflush(stdin)
,那是错误的;这是未定义的行为。未定义的行为并不意味着一定会有错误的行为。请尝试删除
fflush(stdin)
。如果您的程序中断,则代码在其他地方有问题。@iharob Undefined behavior意味着任何事情都可能发生。明天可能会和今天不一样。