【问题标题】:Concatenate double from #define with string in C将#define中的double与C中的字符串连接起来
【发布时间】:2020-06-21 06:08:51
【问题描述】:

在 C 中,我试图让输出文件名包含 2 个变量以便于识别。这些是通过#define obj1 100#define obj2 5 早期启动的,当涉及到输出时,我在文件名之后是100_5_outputOfCode.txt

为了让它发挥作用,我已经尝试过

char fileName[1024];
strcpy(fileName, obj1);
strcat(fileName, "_");
strcat(fileName, obj2);
strcat(fileName, "_");
strcat(fileName, "outputOfCode.txt");

然后在输出函数中使用fileName(正常工作)。相反,我收到一条错误消息ror: passing 'double' to parameter of incompatible type 'const char *'

从这里我尝试通过printf(obj1, %f)obj1obj2 转换为字符,但这没有任何效果。

如何实现将这些对象连接到字符串的目标?我对 C 的了解很少,如果有些不清楚,请见谅。

【问题讨论】:

  • 制作像#define obj1 "100"#define obj2 "5"这样的宏。有了这个,你的第一种方法应该可以工作。
  • 请提供minimal verifiable example 来说明问题。实际上,您的描述非常不清楚。您的代码中的任何地方都没有“双重”。该错误来自哪一行代码?
  • @Eraklon 它们被定义为在我的代码中用作变量的数字,因此将它们定义为字符会导致更多问题。

标签: c string double concatenation


【解决方案1】:
#define obj1 100

给你一个 整数, 你不能直接与strcat 一起使用。如果您想这样做,则必须使用 string:

#define obj1 "100"

但是,您可以保留现有的代码,只需用更简单的代码替换该代码:

char fileName[1024];
sprintf(fileName, "%d_%d_outputOfCode.txt", obj1, obj2);

【讨论】:

  • 甚至:char *filename = obj1 "_" obj2 "_outputOfCode.txt"; then
  • 我已经使用了您解决方案的第二部分,并且效果很好!谢谢!
猜你喜欢
  • 2022-01-03
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 2017-04-17
  • 1970-01-01
  • 2014-08-30
相关资源
最近更新 更多