It is best to understand that scanf
is a function written in the 70's to read tokens from streams. It may be convenient to extract integers, or strings in an interactive program - but it comes from a time when interactive programs were Well less interactive than those of today. Even programs designed to work only from the command line today (for example, git
) have a sophisticated interface compared to what the scanf lets you do.
So one thing to keep in mind is that using standard input in C, whether with scanf
or with other functions is a palliative while learning to program and for small exercises. A serious, large system, even if it has its "pure" C core, must use an interface library or framework to create the interface - such as gobject
, or C ++, boost
, or Qt
. Possibly you can even have all the interface part written in a high level language, and only the internal loops, where "brute force" is needed done in C.
That said - scanf is very counterintuitive for beginners. He just reads the tokens you send - and if there's anything left in the stdin, there's nothing left in the stdin. And there will always be at least \n
, unless you read a token %s
or last. An alternative is to use scanf
followed by fgets
that always reads a string to the end (or only fgets
if you only want a string).