小编use*_*231的帖子

scanf/field lengths:使用变量/宏,C/C++

如何在使用scanf时使用变量指定字段长度.例如:

char word[20+1];
scanf(file, "%20s", word);
Run Code Online (Sandbox Code Playgroud)

另外,使用20 + 1是否正确(因为它需要在末尾添加\ 0?).相反,我希望有类似的东西:

#define MAX_STRING_LENGTH 20
Run Code Online (Sandbox Code Playgroud)

然后

char word[MAX_STRING_LENGTH+1];
scanf(file, "%"MAX_STRING_LENGTH"s", word); // what's the correct syntax here..?
Run Code Online (Sandbox Code Playgroud)

这可能吗?如果它是一个变量如何:

int length = 20;
char word[length+1];
scanf(file, "%" length "%s", word); // what's the correct syntax here..?
Run Code Online (Sandbox Code Playgroud)

谢谢.

c c++ field scanf

5
推荐指数
1
解决办法
4069
查看次数

标签 统计

c ×1

c++ ×1

field ×1

scanf ×1