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?
Description. The sscanf() function reads data from buffer into the locations that are given by argument-list. Each argument must be a pointer to a variable with a type that corresponds to a type specifier in the format-string.
Your sscanf(string, " %d %c") will return EOF , 0 , 1 or 2 : 2 : If your input matches the following. [Optional spaces][decimal digits1][Optional spaces][any character][following data not read]
The width fieldNo more than width characters get converted and stored in the corresponding argument . Fewer than width characters may be read if a whitespace character or a character that can't be converted according to the given format occurs before width is reached. char str[21]; scanf_s("%20s", str, 21);
Field width specifiers are format specifiers used in programming languages for printing formatted output on the screen. In C programming language,format specifiers are of the following types: %i or %d for int. %c for char. %f for float.
Like Stefan said, but for sscanf()
to more properly answer the question, and with a bit more macro trickery:
#define MACRO_SIZE 5
#define FORMAT(S) "%" #S "s"
#define RESOLVE(S) FORMAT(S)
char buf[MACRO_SIZE + 1];
sscanf(input_str, RESOLVE(MACRO_SIZE), buf);
This uses C's automatic joining together of adjacent string literals, to form the required formatting string at compile-time. This only works if MACRO_SIZE
is a preprocessor macro, not if it's a normal runtime variable.
The extra macro call through RESOLVE()
is needed since otherwise the argument would not be resolved to its #define
d value, and we'd end up with a formatting string of "%MACRO_SIZEs"
, which is not what we want.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With