-1

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);
TacoCat
  • 459
  • 4
  • 21

1 Answers1

3

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.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97