Search code examples
cfgets

Calling fgets() twice causes second call to not complete


I have been Googling this problem for hours and so far I haven't seen any mention of it.

int getInt()
{
    char* rawin = (char*)malloc(100);
    printf("How big should the secret code be?\n(Input number of elements):\n");

    while(fgets(rawin, 100, stdin) != NULL)
    {
        if (sscanf(rawin,"%d") == 1)
        {
          break;
        }
        printf("Numbers only please.\n");
    }
    int in = atoi(rawin);
    free(rawin);
    return in;
}

If I call this function twice, whichever one I call first works fine, but the second behaves strangely. Rather than entering the while loop, the program behaves as if looping indefinitely over fgets. The second call of fgets never completes, so never returns anything. When debugging, breakpoints placed anywhere after "while(fgets...", including after the loop, are never reached. I have tried appending "\n", "\0" and "\n\0" to the end of stdin, which did nothing. I have tried 'flushing' stdin by reading out every character that isn't '\n' or \0', which also did nothing.

Edit: To clarify, the condition in the 'if' statement is a placeholder.


Solution

  • You need to store the data someplace:

    if (sscanf(rawin,"%d") == 1)
    

    That is, your sscanf() needs a third argument: a pointer to an integer where you want to store the result of this conversion:

    int in;
    if (sscanf(rawin,"%d",&in) == 1)
    

    You don't need to call atoi() after this.


    As a side note, there's no need for dynamically allocated memory in your example. A simple array would suffice:

    char rawin[100];