将字符串文字与 char 文字连接起来

编程入门 行业动态 更新时间:2024-10-23 20:23:40
本文介绍了将字符串文字与 char 文字连接起来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想连接字符串文字和字符文字.由于语法不正确,"abc" 'd' "efg" 会导致编译器错误:

I want to concat a string literal and char literal. Being syntactically incorrect, "abc" 'd' "efg" renders a compiler error:

x.c:4:24: 错误:预期为 ',' 或 ';'在'd'之前

x.c:4:24: error: expected ',' or ';' before 'd'

现在我必须使用 snprift(不必要地),尽管在编译时知道字符串文字和字符文字的值.

By now I have to use snprift (needlessly), despite the value of string literal and the char literal being know at compile time.

我试过了

#define CONCAT(S,C) ({ static const char *_r = { (S), (C) }; _r; })

但它不起作用,因为 S 的空终止符没有被剥离.(除了给出编译器警告.)

but it does not work because the null terminator of S is not stripped. (Besides of giving compiler warnings.)

有没有办法写一个宏来使用

Is there a way to write a macro to use

  • "abc" MACRO('d') "efg" 或
  • MACRO1(MACRO2("abc", 'd'), "efg") 或
  • MACRO("abc", 'd', "efg") ?
  • "abc" MACRO('d') "efg" or
  • MACRO1(MACRO2("abc", 'd'), "efg") or
  • MACRO("abc", 'd', "efg") ?

如果有人问我为什么要这样:char 字面量来自库,我需要将字符串作为状态消息打印出来.

In case someone asks why I want that: The char literal comes from a library and I need to print the string out as a status message.

推荐答案

如果你能接受单引号,你可以使用字符串化:

If you can live with the single quotes being included with it, you could use stringification:

#define SOME_DEF 'x' #define STR1(z) #z #define STR(z) STR1(z) #define JOIN(a,b,c) a STR(b) c int main(void) { const char *msg = JOIN("Something to do with ", SOME_DEF, "..."); puts(msg); return 0; }

取决于可能合适或不合适的上下文,但就以这种方式说服它实际上是字符串文字而言,这是在运行时无需格式化的唯一方法.

Depending on the context that may or may not be appropriate, but as far as convincing it to actually be a string literal buitl this way, it's the only way that comes to mind without formatting at runtime.

更多推荐

将字符串文字与 char 文字连接起来

本文发布于:2023-07-28 14:10:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1231646.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文字   字符串   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!