Can I use scanf to capture a directive with the width specified by a variable?
I have the following code:
scanf(" %Xs %Ys", buf1, buf2);
Where X and Y must be integers. The problem is that the values for X and Y are compile time constants, and even if I would like to hard-code the values into a format string, I cannot because I don't know the values. In printf, you can send a width variable along with arguments with "% * s". Is there something similar for scanf?
EDIT: To clarify, the constants are known at compile time, but not at coding time, and not from me at all. They can vary by platform or implementation, and they can change after I'm done. Even they didn't, I still wouldn't want to have buffer sizes duplicated in format strings, ready for the fact that I forgot to synchronize them.
source to share
You can create a format string using sprintf ():
sprintf( format, " %%%is %%%is", X, Y );
scanf(format, buf1, buf2);
EDIT: Surprisingly, the following gcc code works:
#include <stdio.h>
#define LIST(...) __VA_ARGS__
#define scanf_param( fmt, param, str, args ) { \
char fmt2[100]; \
sprintf( fmt2, fmt, LIST param ); \
sscanf( str, fmt2, LIST args ); \
}
enum { X=3 };
#define Y X+1
int main(){
char str1[10], str2[10];
scanf_param( " %%%is %%%is", (X,Y), " 123 4567", (&str1, &str2) );
printf("str1: '%s' str2: '%s'\n", str1, str2 );
}
source to share
The problem is that the values for X and Y are compile time constants
Then use the macro insert function:
#include <stdio.h>
#define TEST 2
#define CONST_TO_STRING_(x) #x
#define CONST_TO_STRING(x) CONST_TO_STRING_(x)
int main() {
printf("1 " CONST_TO_STRING(TEST) " 3\n");
return 0;
}
source to share
Your question is not clear. If you don't know the meaning, then these are probably run-time constants, not compile-time constants.
If this is the case (i.e. they are temporary constants), then no, there is no such function in 'scanf'. The only thing you can do is create a complete format string (with specific values embedded in it) at run time using "sprintf" and then pass that format string to your "scanf".
source to share