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