Max string length using scanf -> ANSI C

后端 未结 5 1303
情歌与酒
情歌与酒 2020-11-30 13:14

I have:

#define MAX_STR_LEN 100

and I want to put into scanf pattern so I can control the string length:

scanf         


        
5条回答
  •  猫巷女王i
    2020-11-30 13:43

    Recommend the fgets(buffer, sizeof(buffer), stdin) approach.

    If you still want to use scanf() you can create its format at runtime.

    #define MAX_STR_LEN 100
    char format[2 + sizeof(size_t)*3 + 4 + 1];  // Ugly magic #
    sprintf(format, " %%%zu[^\n]", (size_t) MAX_STR_LEN);
    scanf(format, sometext);
    

    or re-define MAX_STR_LEN to be a string

    #define MAX_STR_LEN "100"
    scanf(" %" MAX_STR_LEN "[^\n]", sometext);
    

    Still recommend the fgets().
    Note fgets() will put leading spaces and the trailing \n in your buffer whereas " %[^\n]" will not.
    BTW: the trailing s in your formats is not likely doing what you think.

提交回复
热议问题