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

后端 未结 5 1724
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  庸人自扰
    2021-01-03 05:26

    If you're using regular scanf (Linux), you have two solutions :

    #define MAX_STRING_LENGTH_STR "20"
    scanf(file, "%"MAX_STRING_LENGTH_STR"s", word);
    

    OR

    #define MAX_STRING_LENGTH 20
    sprintf(format, "%%%ds", MAX_STRING_LENGTH);
    scanf(file, format, word);
    

    However, it seems to be use this code with Visual Studio :

    char str[21];
    scanf("%20s", str, 21);
    

提交回复
热议问题