gpt4 book ai didi

c++ - 如何在 C 宏中连接变量字符串和文字字符串?

转载 作者:搜寻专家 更新时间:2023-10-31 02:02:20 24 4
gpt4 key购买 nike

我正在创建一个接受 2 个字符串的宏:变量字符串和文字字符串。如何将它们组合成一个接受单个变量的函数?

我知道我们可以在宏中组合 2 个文字字符串。

#define LOGPRINT(x,y) func(x y)
#define LOGPRINTSINGLE(x) func(x)

func(char *fmt)
{
printf(fmt);
}

下面的代码工作正常:

char * test = "hey "; 

LOGPRINT("hello ", "world!");
LOGPRINTSINGLE(hey);

但是下面的代码失败了。

LOGPRINT(test, "world!");

如何在宏中将可变字符串测试与文字字符串“world”组合?预期结果是“hey world”被传递给 func()。

**编辑/注意:规则是我只允许更改这边的代码,而不是调用者和 func()。

最佳答案

也许不是世界上最漂亮或最安全的宏,但它确实有效:-)

#include <stdio.h>
#include <string.h>

#define LOGPRINT(x,y) \
{ \
char dest[strlen(x) + strlen(y) + 1]; \
memcpy(dest, x, strlen(x)); \
memcpy(dest + strlen(x), y, strlen(y)); \
dest[strlen(x) + strlen(y)] = 0; \
func(dest); \
}
#define LOGPRINTSINGLE(x) func(x)

void func(char *fmt)
{
printf(fmt);
}


int main()
{
char * test = "hey ";

LOGPRINT("hello ", "world!");
printf("\n");
LOGPRINTSINGLE(test);
printf("\n");
LOGPRINT(test, "world!");

return 0;
}

输出:

hello world!
hey
hey world!

关于c++ - 如何在 C 宏中连接变量字符串和文字字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57406786/

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