简体   繁体   中英

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

I wrote a Tic Tac Toe game, using tutorials. 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(); and how to they interact with each other?

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

From fgets manual

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 .

You can then try to convert the two character string to a number using strtol .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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