Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
Why does everyone say not to use scanf? What should I use instead?
Why does everyone say not to use scanf? What should I use instead?
✍: Guest
scanf has a number of problems, its %s format has the same problem that gets() has --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. You have very little opportunity to do any error recovery.
Yet interactive user input is the least structured input there is. A well-designed user interface will allow for the possibility of the user typing just about anything--not just letters or punctuation when digits were expected, but also more or fewer characters than were expected, or no characters at all (i.e. just the RETURN key), or premature EOF, or anything. It's nearly impossible to deal gracefully with all of these potential problems when using scanf; it's far easier to read entire lines (with fgets or the like), then interpret them, either using sscanf or some other techniques. (Functions like strtol, strtok, and atoi are often useful; If you do use any scanf variant, be sure to check the return value to make sure that the expected number of items were found. Also, if you use %s, be sure to guard against buffer overflow.
Note, by the way, that criticisms of scanf are not necessarily indictments of fscanf and sscanf. scanf reads from stdin, which is usually an interactive keyboard and is therefore the least constrained, leading to the most problems. When a data file has a known format, on the other hand, it may be appropriate to read it with fscanf. It's perfectly appropriate to parse strings with sscanf (as long as the return value is checked), because it's so easy to regain control, restart the scan, discard the input if it didn't match, etc.
2015-10-21, 1160👍, 0💬
Popular Posts:
What are the different storage classes in C? C has three types of storage: automatic, static and all...
How To Set session.gc_maxlifetime Properly? - PHP Script Tips - Understanding and Using Sessions As ...
How To Increment Dates by 1? - Oracle DBA FAQ - Understanding SQL Basics If you have a date, and you...
How To Merge Cells in a Column? - XHTML 1.0 Tutorials - Understanding Tables and Table Cells If you ...
How To Enter Microseconds in SQL Statements? - MySQL FAQs - Introduction to SQL Date and Time Handli...