I have the following code:
scanf(\" %Xs %Ys\", buf1, buf2);
Where X and Y should be integers. The problem is that the values for X and Y ar
The problem is that the values for X and Y are compile-time constants
Then use macro paste feature:
#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;
}
Your question is not clear. If you don't know the values, then they are probably run-time constants, not compile-time constants.
If that's the case (i.e. they are run-time consants), then no, there's no such feature in 'scanf'. The only thing you can do is to produce the complete format string (with the concrete values embedded in it) at run-time by using 'sprintf' and then pass that format string to your 'scanf'.
You may produce the format string with sprintf():
sprintf( format, " %%%is %%%is", X, Y );
scanf(format, buf1, buf2);
EDIT: amazing, but the following gcc code is working:
#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 );
}