我正在创建一个接受2个字符串的宏:变量字符串和文字字符串。如何将它们两者结合到接受单个变量的函数中?
我知道我们可以在宏中组合2个文字字符串。
https://{organization}.visualstudio.com/{Project}/_apis/git/repositories/{Repository ID}/items?path=WAP/WAP.Tests/Properties/AssemblyInfo.cs
以下代码可以正常工作:
#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);
如何在宏中将变量字符串测试与文字字符串“ world”组合在一起? 预期结果是将“嘿世界”传递给func()。
**编辑/注意:规则仅允许我在此侧更改代码,而不能更改调用方和func()。
答案 0 :(得分:1)
也许不是世界上最漂亮或最安全的宏,但是它可以工作:-)
#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!
答案 1 :(得分:1)
如果包含“字符串” STL,则使用c ++字符串非常简单
更改#define LOGPRINT(x,y) func(x y)
到#define LOGPRINT(x,y) func((std::string(x) + std::string(y)).data())
或#define LOGPRINT(x,y) func(std::string(x).append(y).data())