This question already has answers here:
Closed 5 years ago.
Can I use scanf to capture a directive with a width specified by a variable?
(3个答案)
所以我的原始代码是:
scanf("%20s %20s", Player1.name, Player2.name);

如果我想让我的代码更灵活,我能做,还是有类似的方法来做:
.#define MAX_NAME_IN 20
...
scanf("%MAX_NAME_INs %MAX_NAME_INs", Player1.name, Player2.name);
...

最佳答案

#define MAX_NAME_IN 20
#define S_(x) #x
#define S(x) S_(x)
...
scanf("%" S(MAX_NAME_IN) "s %" S(MAX_NAME_IN) "s", Player1.name, Player2.name);

替换为这样的预处理器
S(MAX_NAME_IN) => S_(20) => "20"

scanf("%" S(MAX_NAME_IN) "s %" S(MAX_NAME_IN) "s", Player1.name, Player2.name);
↓
scanf("%" "20" "s %" "20" "s", Player1.name, Player2.name);

编译器将"%" "20" "s %" "20" "s"解释为"%20s %20s"

07-27 22:20