C语言中连接两个字符串的宏
我正在尝试定义一个宏,该宏假定采用 2 个字符串值并返回它们,它们之间用一个空格连接起来。看来我可以使用除空格之外的任何字符,例如:
#define conc(str1,str2) #str1 ## #str2
#define space_conc(str1,str2) conc(str1,-) ## #str2
space_conc(idan,oop);
space_conc
将返回“idan-oop”
我想要返回“idan oop”,有建议吗?
I'm trying to define a macro which is suppose to take 2 string values and return them concatenated with a one space between them. It seems I can use any character I want besides space, for example:
#define conc(str1,str2) #str1 ## #str2
#define space_conc(str1,str2) conc(str1,-) ## #str2
space_conc(idan,oop);
space_conc
would return "idan-oop"
I want something to return "idan oop", suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试
这个 '##' 用于连接符号,而不是字符串。在 C 中,字符串可以简单地并置,编译器将连接它们,这就是这个宏的作用。首先将 str1 和 str2 转换为字符串(如果您像这样使用它
space_conc(hello, world)
,那么我们可以说“hello”和“world”),然后使用简单的单字符将它们彼此相邻放置空格,中间的字符串。也就是说,编译器将像这样解释生成的扩展,并将其连接到
HTH
Edit
为了完整起见,宏扩展中的“##”运算符是这样使用的,假设您
将得到以下结果,如果调用为
dumb_macro(hello, world)
,它不是一个字符串,而是一个符号,您可能会遇到未定义符号错误,表示“helloworld”不存在,除非您先定义它。这是合法的:
Try this
The '##' is used to concatenate symbols, not strings. Strings can simply be juxtaposed in C, and the compiler will concatenate them, which is what this macro does. First turns str1 and str2 into strings (let's say "hello" and "world" if you use it like this
space_conc(hello, world)
) and places them next to each other with the simple, single-space, string inbetween. That is, the resulting expansion would be interpreted by the compiler like thiswhich it'll concatenate to
HTH
Edit
For completeness, the '##' operator in macro expansion is used like this, let's say you have
will result in the following if called as
dumb_macro(hello, world)
which is not a string, but a symbol and you'll probably end up with an undefined symbol error saying 'helloworld' doesn't exist unless you define it first. This would be legal:
正确的做法是将 2 根琴弦并排放置。 “##”不起作用。只是:
The right was to do it is to place the 2 strings one next to the other. '##' won't work. Just: