Can I use scanf to capture a directive with a width specified by a variable?

后端 未结 3 799
梦毁少年i
梦毁少年i 2020-12-20 01:24

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

相关标签:
3条回答
  • 2020-12-20 01:51

    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;
    }
    
    0 讨论(0)
  • 2020-12-20 01:52

    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'.

    0 讨论(0)
  • 2020-12-20 02:11

    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 );
    }
    
    0 讨论(0)
提交回复
热议问题