home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / alt / hackers / 1146 < prev    next >
Encoding:
Text File  |  1992-07-23  |  2.1 KB  |  67 lines

  1. Path: sparky!uunet!wupost!tulane!ukma!rutgers!att!cbfsb!cbnewsg.cb.att.com!cooper
  2. From: cooper@cbnewsg.cb.att.com (Ralph 'Hairy' Moonen)
  3. Newsgroups: alt.hackers
  4. Subject: Re: not a test
  5. Summary: sscanf *&^*&#%$^*#
  6. Message-ID: <1992Jul23.075512.21400@cbfsb.cb.att.com>
  7. Date: 23 Jul 92 07:55:12 GMT
  8. References: <1992Jul20.185304.837@amhux2.amherst.edu> <ik89NB1w164w@kzdoos.hacktic.nl>
  9. Sender: news@cbfsb.cb.att.com
  10. Organization: AT&T
  11. Lines: 53
  12. Approved: news@rutgers.rutgers.edu
  13.  
  14. In article <ik89NB1w164w@kzdoos.hacktic.nl>, koos@kzdoos.hacktic.nl (Koos van den Hout) writes:
  15. > ObHack : In a program I'm working on I need to parse lines that are in
  16. > the form :
  17. > <name> <value> <value> <string> [<string>...]
  18. > So 'group_A 0 0 aaa' is valid but 'group_B 10 0 bb1 bb2 bb3' also.
  19. > Problem : How to parse this when the complete line is already stored in memory?
  20. > Solution:
  21. > The line is stored in char buf[512];
  22. > int nm,inc;
  23. > sscanf(buf,"%s %d %d%n",name,&val1,&val2,nm);
  24. > /* do something with the name and val1 and val2 */
  25. > while(sscanf(&buf[nm],"%s%n",member,&inc)==1){
  26. >    nm+=inc;
  27. >    /* do something with member */
  28. > }
  29.  
  30. And you loose brownie points for using sscanf. I wouldn't trust it anytime.
  31. Even a slight alteration of the format, or a corruption thereof can send
  32. sscanf into the twilight zone. Apart from the fact that sscanf does a lot of
  33. conversion, that costs a lot of time. What about this solution:
  34.  
  35. char buf[512];
  36. char *flds[256];
  37.  
  38. register int cntr = 0;
  39. register short suffix = 2;
  40.  
  41. flds[1] = buf;
  42.  
  43. while(buf[cntr++] != NULL)    {
  44.     if(buf[cntr] == ' ')    flds[suffix++] = &buf[cntr + 1];
  45.     }
  46.  
  47. You now have an array pointers to all fields in the line. The only
  48. thing you have to do now is do an atoi() for the two numerical values.
  49.  
  50. This should work much faster, and is easier to change for later 
  51. modifications, because the parsing bit doesn't have to change.
  52.  
  53. Of course you could use getopts() :-)
  54.  
  55. --Ralph Moonen
  56. --rmoonen@hvlpa.att.com
  57. --AT&T Hilversum, The Netherlands
  58. -- 
  59. begin 644 ralph.pub
  60. MF58  ]M2*@QR86QP:%]M;V]N96[^ 6- RJ-V"2/)B4[K']_ZR@4#IVQE=TT6
  61. LHD.M[5JN9O_E1]Z9HXM/%A$WW.E[OA8>ES0S+;I@Q::BY.J8/Z]22#4% !$6
  62. end
  63.