0

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); } 
2
  • 2
    You need to use sprintf family to create the final format string, then use it with sscanf. Commented Oct 11, 2022 at 16:29
  • 2
    Why do you need to do this? This sounds like kind of a strange constraint. Is this a programming assignment where you've been told which library functions you may and may not use? Normally, the way to break a line up into fields, based on a programmable delimiter, would involve strtok. Commented Oct 11, 2022 at 17:50

1 Answer 1

2

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 */ } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.