home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #26 / NN_1992_26.iso / spool / comp / programm / 3127 < prev    next >
Encoding:
Internet Message Format  |  1992-11-12  |  2.2 KB

  1. Path: sparky!uunet!dtix!darwin.sura.net!zaphod.mps.ohio-state.edu!magnus.acs.ohio-state.edu!usenet.ins.cwru.edu!agate!dog.ee.lbl.gov!horse.ee.lbl.gov!torek
  2. From: torek@horse.ee.lbl.gov (Chris Torek)
  3. Newsgroups: comp.programming
  4. Subject: Re: HELP with scanf/getchar!
  5. Message-ID: <27401@dog.ee.lbl.gov>
  6. Date: 12 Nov 92 12:30:05 GMT
  7. References: <1992Nov9.162547.11163@seas.smu.edu> <1992Nov9.205548.5984@bcrka451.bnr.ca> <s1110238.721534396@giaeb>
  8. Reply-To: torek@horse.ee.lbl.gov (Chris Torek)
  9. Followup-To: comp.lang.c
  10. Organization: Lawrence Berkeley Laboratory, Berkeley
  11. Lines: 38
  12. NNTP-Posting-Host: 128.3.112.15
  13.  
  14. I was going to stay out of this; the original question should have been
  15. sent to comp.lang.c, not comp.programming.
  16.  
  17. In article <s1110238.721534396@giaeb> s1110238@giaeb.cc.monash.edu.au
  18. (Lee Hollingworth) provides a workable (if a bit buggy; it will loop
  19. forever if EOF occurs without a newline).  solution.  Along the way to
  20. that particular article (see references: line), however, a lot of
  21. incorrect advice went out.
  22.  
  23. The original problem was caused by the call
  24.  
  25.     scanf("%d\n", ...)
  26.  
  27. In the C language, this means to read through standard input, as follows:
  28.  
  29.     - skip any leading white space, including newlines;
  30.  
  31.     - read and convert an integer, storing the result through the
  32.       pointer provided; and (here comes the problem)
  33.  
  34.     - skip any further white space, including newlines.
  35.  
  36. The last is a result of the `\n' directive.  It does not just skip
  37. `current' white space, but also `future' white space.  In order to get
  38. the future white space, it will read the next line (and any subsequent
  39. lines as needed) until it encounters EOF or a non-white-space character.
  40.  
  41. This may seem like a bizarre thing to do.  Well, it is.  On the whole,
  42. C's scanf() formats are not particularly well designed.  The
  43. comp.lang.c FAQ advises against direct calls to scanf(): line-at-a-time
  44. input should generally be done with calls to fgets followed by calls to
  45. sscanf.
  46.  
  47. Further discussion of C's scanf() belongs in comp.lang.c (but please
  48. read the FAQ first!).  Note that I have redirected followups.
  49. -- 
  50. In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 510 486 5427)
  51. Berkeley, CA        Domain:    torek@ee.lbl.gov
  52.