Search code examples
cgets

How appropriate is the use of the statement fflush(stdin)?


To read multi-word strings, I have been using the gets() function. The behaviour of the gets() function is unpredictable to me and I use the statement fflush(stdin) before every gets() statement to avoid issues. Is using this statement this way appropriate? What can be an alternative approach?


Solution

  • You can use fgets() instead of gets(): https://stackoverflow.com/a/4309760/1758762

    As everyone else said, the canonical alternative to gets() is fgets() specifying stdin as the file stream.

    char buffer[BUFSIZ];
    
    while (fgets(buffer, sizeof(buffer), stdin) != 0)
    {
        ...process line of data...
    }
    

    What no-one else yet mentioned is that gets() does not include the newline but fgets() does. So, you might need to use a wrapper around fgets() that deletes the newline:

    char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
    {
        if (fgets(buffer, buflen, fp) != 0)
        {
            size_t len = strlen(buffer);
            if (len > 0 && buffer[len-1] == '\n')
                buffer[len-1] = '\0';
            return buffer;
        }
        return 0;
    }