如何混合使用字符串文字和浮点数并将它们连接成C中的一个字符串?

Ian*_*Ian 2 c strcat

我对C有点生疏,我想连接几个字符串和浮点数.特别是,我想创建字符串"AbC",其中A和C是字符串文字,b是浮点数.我知道我必须把浮动变成一个字符串,但我的代码没有编译.下面是我的代码,后面是gcc的输出.有关如何修复我的代码的任何建议?

我的计划:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
double b = 0.5;
char mystring[16];
strcpy(mystring,"A");
strcat(mystring,ftoa(b));
strcat(mystring,"C");
printf("%s",mystring);
return 0;
}
Run Code Online (Sandbox Code Playgroud)

GCC输出:

test2.c: In function ‘main’:
test2.c:11:1: warning: passing argument 2 of ‘strcat’ makes pointer from integer without a cast [enabled by default]
 strcat(mystring,ftoa(b));
 ^
In file included from test2.c:3:0:
/usr/include/string.h:137:14: note: expected ‘const char * __restrict__’ but argument is of type ‘int’
 extern char *strcat (char *__restrict __dest, const char *__restrict __src)
              ^
/tmp/cc77EVEN.o: In function `main':
test2.c:(.text+0x42): undefined reference to `ftoa'
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 5

你在寻找的是snprintf:

snprintf(mystring, sizeof mystring, "A%.1fC", b);
Run Code Online (Sandbox Code Playgroud)