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?
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 likescanf(), you can pass the strings you read along tosscanf().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 onstdinwhich you need to drain. Plus, you won’t wind up in the pitfall of mixing line-oriented input withscanf(), which causes headaches when things like\nget left onstdincommonly leading new coders to believe the input calls had been ignored altogether.Something like this might be to your liking:
Above you should note that
fgets()returnsNULLon EOF or error, which is why I wrapped it in anif. Thesscanf()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.