I have a C program that gets the input file delimiter as an argument from the user and stores it in a char
. I then need to sscanf
the input file based on that delimiter that the user has specified.
Is this possible?
Pseudo code:
char delim = getchar( );
....
// Read input file
while(fgets(buf, sizeof buf, in_fp)){
sscanf(buf, "%d[delim]%c[delim]%s", &id, &sex, &dob);
}
CodePudding user response:
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 */ }