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

use*_*231 5 c c++ field scanf

如何在使用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)

谢谢.

tor*_*rak 7

以下应该为第一种情况做你需要的.

#define MAX_STRING_LENGTH 20
#define STRINGIFY(x) STRINGIFY2(x)
#define STRINGIFY2(x) #x

{
  ...
  char word[MAX_STRING_LENGTH+1];     
  scanf(file, "%" STRINGIFY(MAX_STRING_LENGTH) "s", word);
  ...
}
Run Code Online (Sandbox Code Playgroud)

注意:需要两个宏,因为如果您尝试直接使用STRINGIFY2之类的东西,那么您只需获取字符串"MAX_STRING_LENGTH"而不是其值.

For the second case you could use something like snprintf, and at least some versions of C will only let you allocate dynamically sized arrays in the heap with malloc() or some such.