home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / lang / c / 19581 < prev    next >
Encoding:
Internet Message Format  |  1993-01-12  |  1.7 KB

  1. Path: sparky!uunet!crdgw1!rdsunx.crd.ge.com!bart!volpe
  2. From: volpe@bart.NoSubdomain.NoDomain (Christopher R Volpe)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: ** Ack! Help again! **
  5. Message-ID: <1993Jan12.132507.19155@crd.ge.com>
  6. Date: 12 Jan 93 13:25:07 GMT
  7. References: <kaNTwB1w165w@tradent.wimsey.bc.ca> <dschmitz.726261452@pv0321.vincent.iastate.edu> <841@ulogic.UUCP>
  8. Sender: volpe@bart (Christopher R Volpe)
  9. Reply-To: volpe@ausable.crd.ge.com
  10. Organization: GE Corporate Research & Development
  11. Lines: 53
  12. Nntp-Posting-Host: bart.crd.ge.com
  13.  
  14. In article <841@ulogic.UUCP>, hartman@ulogic.UUCP (Richard M. Hartman) writes:
  15.  
  16. [example code showing use of gets after scanf to read up to next newline
  17.  deleted.]
  18.  
  19. |> There should be no need for such a hack.
  20. |> In your scanf(), does the format string contain a "\n"?
  21. |> Try this:
  22. |> 
  23. |>     /* test.c */
  24. |>     #include <stdio.h>
  25. |>     main()
  26. |>     { 
  27. |>     int i; char buf[81];
  28. |> 
  29. |>     fflush(stdin);
  30. |>     scanf("%d", &i);
  31. |>     gets(buf);
  32. |>     printf("[%d], [%s]\n", i, buf);
  33. |> 
  34. |>     fflush(stdin);
  35. |>     scanf("%d\n", &i);
  36. |>     gets(buf);
  37. |>     printf("[%d], [%s]\n", i, buf);
  38. |>     }
  39. |> 
  40. |> log of run:
  41. |> 
  42. |>     $ ./test
  43. |>     23
  44. |>     [23], []
  45. |>     132
  46. |>     fsdljk
  47. |>     [132], [fsdljk]
  48. |>     $
  49. |> 
  50.  
  51. Have you tried this with non-trivial input? Your assumption is wrong. A
  52. newline in the format string will not force a read up to the next newline
  53. in the input. A newline is whitespace, and therefore will simply 
  54. consume whatever whitespace exists before the next field. It will not
  55. skip over superfluous fields on the same line, as the code posted by the
  56. previous poster would. 
  57.  
  58. However, I would use fgets followed by sscanf, rather than scanf followed
  59. by gets. It's safer.
  60.  
  61. -Chris
  62. -- 
  63. ==================
  64. Chris Volpe
  65. G.E. Corporate R&D
  66. volpecr@crd.ge.com
  67.