scanf / field lengths : using a variable / macro, C/C++

后端 未结 5 1755
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 04:49

How can I use a variable to specify the field length when using scanf. For example:

char word[20+1];
scanf(file, \"%20s\", word);

Also, is

5条回答
  •  旧时难觅i
    2021-01-03 05:34

    The following should do what you need for the first case.

    #define MAX_STRING_LENGTH 20
    #define STRINGIFY(x) STRINGIFY2(x)
    #define STRINGIFY2(x) #x
    
    {
      ...
      char word[MAX_STRING_LENGTH+1];     
      scanf(file, "%" STRINGIFY(MAX_STRING_LENGTH) "s", word);
      ...
    }
    

    NOTE: Two macros are required because if you tried to use something like STRINGIFY2 directly you would just get the string "MAX_STRING_LENGTH" instead of its value.

    For the second case you could use something like snprintf, and at least some versions of C will only let you allocate dynamically sized arrays in the heap with malloc() or some such.

提交回复
热议问题