gpt4 book ai didi

c - C 中的字符串化运算符不适用于 linux

转载 作者:太空宇宙 更新时间:2023-11-04 03:35:47 26 4
gpt4 key购买 nike

我有以下代码在 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);

确实,numbersStoString(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 以获取地址)

关于c - C 中的字符串化运算符不适用于 linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32865828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com