Aman Jain Aman Jain - 5 months ago 31
C Question

How to pass variable length width specifier in sscanf?

sscanf(input_str, "%5s", buf); //reads at max 5 characters from input_str to buf

But I need to use something like %MACRO_SIZEs instead of %5s

A trivial solution is to create a format string for the same

char fmt_str[100] = "";
snprintf(fmt_str, 100, "%%%ds", MACRO_SIZE);
sscanf(input_str, fmt_str, buf);

Is there a better way to achieve the same?


if your MACRO_SIZE is const at compile time, you can try this:

#define MACRO_SIZE "5"
snprintf(fmt_str, 100, "%" MACRO_SIZE "s", buf);