First off, never use gets
. There is no way to tell it how big your buffer is, so it will cheerfully write input past the end and make the program blow up. This used to be the number one cause of remotely exploitable security holes in network servers.
Second off, never use any of the *scanf
functions either, because:
- Some
scanf
format strings are just as unsafe as gets
, notably %s
with no size modifiers.
- Numeric overflow inside
scanf
provokes undefined behavior, which means your program may crash simply because someone typed a number that was too big.
- It is extremely difficult to write a robust input parser using
scanf
, because if it fails, it does not tell you precisely where the problem characters were.
For a simple task like this one, you should use fgets
(or, better, getline
if you have it) and convert the age to an integer with strtoul
. (Age cannot be negative, so you want the unsigned version. Don't use atoi
and friends - just like *scanf
, they don't give you enough information about invalid input.)
For more complicated tasks, you should reach for lex
and yacc
.