sscanf question

Discussion of chess software programming and technical issues.

Moderators: hgm, Rebel, chrisw

User avatar
Rebel
Posts: 6991
Joined: Thu Aug 18, 2011 12:04 pm

sscanf question

Post by Rebel »

sscanf seprates items with the whitespace delimiter. Is there any way you can make the whitespace delimiter flexible for strings for instance with a comma?

Example

char buf[100] = "John is male, Ann is female";
char male[100];
char female[100];

sscanf(buf,"%s %s",&male,&female);

printf("%s\n",male);
printf("%s\n",female);

Output:
John
is

But what I want is:

John is male
Ann is female
90% of coding is debugging, the other 10% is writing bugs.
User avatar
hgm
Posts: 27796
Joined: Fri Mar 10, 2006 10:06 am
Location: Amsterdam
Full name: H G Muller

Re: sscanf question

Post by hgm »

You can use a format specifier %[...] instead of %s, where the ... symbolizes the set of characters allowed in the string. This uses the same format as in regular expressions of the 'ed' editor, i.e. a ^ as first character is interpreted as a negation, "everything but". So %[^,\n] would read everything up to a comma or newline.
Joost Buijs
Posts: 1563
Joined: Thu Jul 16, 2009 10:47 am
Location: Almere, The Netherlands

Re: sscanf question

Post by Joost Buijs »

Indeed, so in the example it would be something like:

Code: Select all

	sscanf(buf, "%[^,], %[^\n]", male, female);
Alternatively you could use strtok_s() which I somehow prefer over scanf()
User avatar
Rebel
Posts: 6991
Joined: Thu Aug 18, 2011 12:04 pm

Re: sscanf question

Post by Rebel »

Works, thanks.
90% of coding is debugging, the other 10% is writing bugs.
bob
Posts: 20943
Joined: Mon Feb 27, 2006 7:30 pm
Location: Birmingham, AL

Re: sscanf question

Post by bob »

I also prefer strtok() as it makes it simple if you want to re-parse something with different delimiters. IE if you notice a "/" you might want to re-parse with that to deal with FEN, where in other cases you might not want "/" to be a delimiter (I use "/" for time control settings for example... And then to allow expressions, and then to allow filenames, and then to deal with FEN, each of which is slightly different in how it needs to be handled.