Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable length width specifier in sscanf?

Tags:

c

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?

like image 715
Aman Jain Avatar asked Feb 13 '09 07:02

Aman Jain


People also ask

What is sscanf() in C?

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.

What does sscanf return?

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]

How can the maximum field width for a data item be specified within a Scanf function?

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);

What is field width specifier in C?

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.


2 Answers

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 #defined value, and we'd end up with a formatting string of "%MACRO_SIZEs", which is not what we want.

like image 167
unwind Avatar answered Oct 07 '22 21:10

unwind


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);
like image 26
Stefan Avatar answered Oct 07 '22 21:10

Stefan