Why does everyone say not to use scanf? What should I use instead?
scanf has a number of problems--see questions 12.17, 12.18, and 12.19. Also, its %s format has the same problem that gets() has (see question 12.23)--it's hard to guarantee that the receiving buffer won't overflow.
More generally, scanf is designed for relatively structured, formatted input (its name is in fact derived from ``scan formatted''). If you pay attention, it will tell you whether it succeeded or failed, but it can tell you only approximately where it failed, and not at all how or why. It's nearly impossible to do decent error recovery with scanf; usually it's far easier to read entire lines (with fgets or the like), then interpret them, either using sscanf or some other techniques. (Routines like strtol, strtok, and atoi are often useful; see also question 13.6.) If you do use sscanf, don't forget to check the return value to make sure that the expected number of items were found.
References:
K&R2 Sec. 7.4 p. 159
Read sequentially: prev next up top
This page by Steve Summit // Copyright 1995 // mail feedback