简体   繁体   English

在 C 中使用 ## 运算符连接字符串

[英]Concatenate strings using ## operators in C

In C we can use ## to concatenate two arguments of a parameterized macro like so:在 C 中,我们可以使用 ## 连接参数化宏的两个 arguments,如下所示:

arg1 ## arg2 which returns arg1arg2 arg1 ## arg2返回arg1arg2

I wrote this code hoping that it would concatenate and return me a string literal but I cannot get it to work:我写了这段代码,希望它能连接并返回一个字符串文字,但我无法让它工作:

#define catstr(x, y) x##y

puts("catting these strings\t" catstr(lmao, elephant));

returns the following error:返回以下错误:

define_directives.c:31:39: error: expected ‘)’ before ‘lmaoelephant’
   31 |         puts("catting these strings\t" catstr(lmao, elephant));
      |                                       ^
      |                                       )

It seems the strings are concatenating but they need to be wrapped around quotes in order for puts to print it.看起来字符串是串联的,但它们需要用引号括起来以便puts打印它。 But doing so, the macro no longer works.但是这样做,宏不再起作用。 How do I get around this?我该如何解决这个问题?

You do not need to use ## to concatenate strings.您不需要使用##来连接字符串。 C already concatenates adjacent strings: "abc" "def" will become "abcdef" . C 已经连接了相邻的字符串: "abc" "def"将变为"abcdef"

If you want lmao and elephant to become strings (without putting them in quotes yourself for some reason), you need to use the stringize operator, # :如果你想让lmaoelephant变成字符串(出于某种原因而不是自己将它们放在引号中),你需要使用 stringize 运算符#

#define string(x) #x

puts("catting these strings\t" string(lmao) string(elephant));

To use the call to puts() in this way, the macro catstr() should be constructed to do two things:要以这种方式使用对puts()的调用,应构造宏catstr()来做两件事:

  • stringify and concatenate lmao to the string "catting these strings\t"字符串化并将lmao连接到字符串"catting these strings\t"
  • stringify and concatenate elephant to lmao .elephant字符串化并连接到lmao

You can accomplish this by changing your existing macro definition from:您可以通过更改现有的宏定义来完成此操作:

#define catstr(x, y) x##y

To:到:

#define catstr(x, y) #x#y

This essentially result in:这基本上导致:

"catting these strings\t"#lmao#elephant

Or:要么:

"catting these strings   lmaoelephant"  

Making it a single null terminated string, and suitable as an argument to puts() :使它成为一个以 null 结尾的字符串,并且适合作为puts()的参数:

puts("catting these strings\t" catstr(lmao, elephant));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM