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

user1115057 picture user1115057 · Feb 14, 2012 · Viewed 56k times · Source

Many people said that scanf shouldn't be used in "more serious program", same as with getline.

I started to be lost: if every input function I got across people said that I shouldn't use any of them, then what should I use? Is there is a more "standard" way to get input that I'm not aware of?

Answer

FatalError picture FatalError · Feb 14, 2012

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.