Path: utzoo!utgpu!water!watmath!clyde!bellcore!decvax!decwrl!purdue!gatech!uflorida!novavax!proxftl!jesse From: jesse@proxftl.UUCP (Jesse Perry) Newsgroups: comp.lang.c Subject: Re: printf vs fprintf Summary: Don't encourage use of scanf(), fscanf() Keywords: Style Message-ID: <200@proxftl.UUCP> Date: 20 May 88 13:44:08 GMT References: <2454@ritcsh.UUCP> Organization: Proximity Technology, Ft. Lauderdale Lines: 35 In article <2454@ritcsh.UUCP>, gregory@ritcsh.UUCP (Gregory Conway) writes: >The >point is really simple, don't use printf and scanf. Use, instead, >fprintf (stdout, "....") and fscanf (stdin, "....", &whatever). Please, PLEASE don't tell people to use either scanf() or fscanf(). Instead use gets() or fgets(), followed by sscanf(). Code which uses scanf() or fscanf() is susceptible to a nasty problem if the input stream is not correctly formatted. The problem is that these functions do not stop reading input at end of line. They only stop when each % item in the control string has been matched (or EOF is found). If the user fails to enter all the fields expected by the control string, the (f)scanf() function will assume that the missing data is on the following line(s). If this happens with scanf(), the program appears to hang -- it is waiting for the user to enter that next line, but the user won't because he is waiting for the results of the line he just entered (unaware that the entered line is incomplete). If the input stream for fscanf() is incorrect, the program will not (typically) hang, but it will mung the input lines together in crazy ways, and not report any error. Using (f)gets() followed by sscanf() is much more reliable, since format errors can be detected and reported immediately. >Gregory Conway@Computer Science House UUCP: ...rochester!ritcv!ritcsh!gregory >Rochester Institute of Technology, Rochester, NY Jesse Perry (RIT '87 :-) UUCP: uunet!proxftl!jesse BITNET: allegra!novavax!proxftl@psuvax1.uucp ARPA: sunvice!proxftl!jesse@sun.com