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

后端 未结 5 1708
伪装坚强ぢ
伪装坚强ぢ 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:30

    There's a difference here between C90, C99, and C++. In C++, you can use any integral constant expression, so

    const int max_string_size = 20;
    int this_string[max_string_size + 1];
    

    is legal. In C99, the expression doesn't have to be constant; if it isn't, you get a variable length array. In the older C90, the expression couldn't include variables, so the above would not compiler, and you'd have to use

    #define MAX_STRING_SIZE 20
    char this_string[MAX_STRING_SIZE + 1];
    

提交回复
热议问题