Specifying the maximum string length to scanf dynamically in C (like “%*s” in printf)

后端 未结 3 340
小蘑菇
小蘑菇 2020-12-06 04:51

I can specify the maximum amount of characters for scanf to read to a buffer using this technique:

char buffer[64];

/* Read one li         


        
3条回答
  •  执念已碎
    2020-12-06 05:20

    There is indeed no variable width specifier in the scanf family of functions. Alternatives include creating the format string dynamically (though this seems a bit silly if the width is a compile-time constant) or simply accepting the magic number. One possibility is to use preprocessor macros for specifying both the buffer and format string width:

    #define STR_VALUE(x) STR(x)
    #define STR(x) #x
    
    #define MAX_LEN 63
    
    char buffer[MAX_LEN + 1];
    fscanf(file, "%" STR_VALUE(MAX_LEN) "[^\n]", buffer);
    

提交回复
热议问题