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
sscanf question
Moderators: hgm, Rebel, chrisw
-
- Posts: 6991
- Joined: Thu Aug 18, 2011 12:04 pm
sscanf question
90% of coding is debugging, the other 10% is writing bugs.
-
- Posts: 27796
- Joined: Fri Mar 10, 2006 10:06 am
- Location: Amsterdam
- Full name: H G Muller
Re: sscanf question
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.
-
- Posts: 1563
- Joined: Thu Jul 16, 2009 10:47 am
- Location: Almere, The Netherlands
Re: sscanf question
Indeed, so in the example it would be something like:
Alternatively you could use strtok_s() which I somehow prefer over scanf()
Code: Select all
sscanf(buf, "%[^,], %[^\n]", male, female);
-
- Posts: 6991
- Joined: Thu Aug 18, 2011 12:04 pm
-
- Posts: 20943
- Joined: Mon Feb 27, 2006 7:30 pm
- Location: Birmingham, AL
Re: sscanf question
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.