You can use sprintf
to create the format string for sscanf
(my_fmt_string
):
char my_fmt_string[32];
sprintf(my_fmt_string, "%%d%c%%c%c%%s", delim, delim);
Note that we use %%
in places where we need the format string to contain the %
character itself for sscanf
.
Then use my_fmt_string
instead of the string literal:
while (fgets(buf, sizeof buf, in_fp))
{
/*----------vvvvvvvvvvvvv-----------------*/
sscanf(buf, my_fmt_string, &id, &sex, &dob);
}
A Final Note:
My answer above is marely attempting to answer the narrow question of dynamic formating.
But in order to use sscanf
properly, you have to verify it succeeded by inspecting the return value. It should be the number of fields parsed (3 in this case):
if (sscanf(buf, my_fmt_string, &id, &sex, &dob) != 3) { /* handle error */ }