Safer input in C

September 10, 2015

Why not to use scanf

scanf is the standard method to get structured, formatted input in C.
The problems with scanf are:

A more detailed explaination is on c-faq.com.

An alternative

A quick search on stackoverflow showed that using fgets to read strings is considered a good option.
To read ints and floats the sscanf function can be used. sscanf is a function used to take formatted “input” from strings.

fgets has another quirk - it reads the '\n' into the string too. This can be resolved by checking the last character. Here’s how I implemented a read_line function that reads strings of given size thus avoiding overflow.

int read_line(char *line, int size)
{
    fgets(line, size, stdin);

    int length = strlen(line);

    if(line[length-1] == '\n')
    {
        line[length-1] = '\0';
        length--;
    }

    return length;
}
 

This function can be used to implement a read_int function that asks the user to re-enter the input if the input is invalid.

int read_int()
{
    char line[256];
    read_line(line, sizeof line);
    int i;
    if(sscanf(line, "%d", &i) == 1)
    {
        return i;
    }
    else
    {
        printf("\"%s\" is not an integer. Retry: ", line);
        return read_int();
    }
}
Safer input in C - September 10, 2015 - Saurabh Mathur