我有以下代码在 Windows 中按预期工作,但在 Ubuntu 上我收到错误“toString1 未在此范围内声明”。
#include <stdio.h>
#define a 2
#define b 3
#define c 4
#define d 5
#define toString1(S) #S
#define toString(S) toString1(S)
#define numbers a,b,c,d
#define numbersS toString(numbers)
int main()
{
int a1 = 0, a2 = 0, a3 = 0, a4 = 0;
if (sscanf_s(numbersS, "%d,%d,%d,%d", &a1, &a2, &a3, &a4) == 4)
{
printf("The numbers were assigned correctly");
}
printf("%d %d %d %d ", a1, a2, a3, a4);
}
这可能是什么原因?如果我删除 toString1 并制作
#define toString(S) #S
Windows 和 Ubuntu 上每个变量的结果都是 0。
谁能解释一下?
编译器说:
error: macro "toString1" passed 4 arguments, but takes just 1
sscanf(numbersS, "%d,%d,%d,%d",a1,a2,a3,a4);
确实,numbersS
是 toString(numbers)
而 numbers 是 a,b,c,d
所以你需要一些变量宏魔法才能正常工作:
#define a 2
#define b 3
#define c 4
#define d 5
#define toString1(S...) #S
#define toString(S...) toString1(S, __VA_ARGS__)
#define numbers a,b,c,d
#define numbersS toString(numbers)
int main()
{
int a1,a2,a3,a4;
sscanf(numbersS, "%d,%d,%d,%d",&a1,&a2,&a3,&a4);
printf("%d %d %d %d", a1,a2,a3,a4);
}
在线:https://ideone.com/puPd6x
(另外,请注意我已经修复了 sscanf 以获取地址)
我是一名优秀的程序员,十分优秀!