While developing a small program to scan lines of English words for key data items, I selected sscanf() to parse the line. Since an unknown number of words exist on each line, sscanf() must be called with the maximum number of possible fields specified in the request. This results in a long and ugly single line statement. A cleaner technique would to used sscanf() to obtain one word at a time in a programmed loop. Unfortunately, it's not possible to know how many spaces sscanf() skipped over to obtain the next field. Thus it's impossible to call sscanf() again with a string pointer that reflects the exact spot where sscanf() left off on the previous call. Code example follows. Two questions: 1) am I missing something in the usage of sscanf()? and 2) is there a better way to do this in c?
#include <stdio.h>
#include <string.h>
/*
* using sscanf to parse a line (null terminated string) with fields (words)
* separated by one or more spaces into an array of words (fields).
*/
void main()
{
int i,j;
int idx;
char string[100] = "word1 word2 word3 word4 word5 word6 word7\0";
char fields[20][10];
#if 1
j=sscanf (&string[0], "%s%s%s%s%s%s", &fields[0][0], &fields[1][0], &fields[2][0], &fields[3][0], &fields[4][0], &fields[5][0]);
printf("sscanf returned: %d\n",j);
#else
/*
* this would be the preferred way to parse a long line of words,
* but there is no way to know with certainty how many spaces sscanf
* skipped over to obtain the next string (word). A modified version
* of sscanf that either modified an integer pointer argument or
* updated the pointer to the input string (line) would allow
* subsequent calls to pick up where the last sscanf call left off.
*
*/
for (i=0,idx=0;i<6;i++){
j=sscanf (&string[idx], "%s", &fields[i][0]);
idx += strlen(&fields[i][0]);
printf("sscanf returned: %d\n",j);
if (j==0)
break;
}
#endif
for (i=0;i<6;i++){
printf("%s",&fields[i][0]);
}
printf("\n");
return;
}