简体   繁体   English

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

[英]fgets(); how does this work inside this part of code? C programming

I wrote a Tic Tac Toe game, using tutorials. 我使用教程编写了一个Tic Tac Toe游戏。 Now I'm just going trough the code to see what i don't understand and I came up with this part, witch is confusing me. 现在,我只是通过代码来查看我不了解的内容,而我想到了这一部分,女巫使我感到困惑。

 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*

How does this part work? 这部分如何工作? I don't even know how to formulate the question. 我什至不知道如何提出这个问题。 Sorry . 对不起 So what are the three values in fgets(); 那么fgets()中的三个值是什么? and how to they interact with each other? 以及他们如何互相影响?

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

From fgets manual 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.

so the fgets() , is taking at most 2 characters from the input stream, or until return key is pressed (sending a '\\n' character) or EOF is sent, and stores the result in userInput . 因此fgets()从输入流中最多获取2个字符,或者直到按下回车键(发送'\\n'字符)或发送EOF userInput ,并将结果存储在userInput

You can then try to convert the two character string to a number using strtol . 然后,您可以尝试使用strtol将两个字符串转换为数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM