Which is the best way to get input from user in C?

Generally, fgets() is considered a good option. It reads whole lines into a buffer, and from there you can do what you need. If you want behavior like scanf(), you can pass the strings you read along to sscanf().

The main advantage of this, is that if the string fails to convert, it’s easy to recover, whereas with scanf() you’re left with input on stdin which you need to drain. Plus, you won’t wind up in the pitfall of mixing line-oriented input with scanf(), which causes headaches when things like \n get left on stdin commonly leading new coders to believe the input calls had been ignored altogether.

Something like this might be to your liking:

char line[256];
int i;
if (fgets(line, sizeof(line), stdin)) {
    if (1 == sscanf(line, "%d", &i)) {
        /* i can be safely used */
    }
}

Above you should note that fgets() returns NULL on EOF or error, which is why I wrapped it in an if. The sscanf() call returns the number of fields that were successfully converted.

Keep in mind that fgets() may not read a whole line if the line is larger than your buffer, which in a “serious” program is certainly something you should consider.

Leave a Comment

tech