我对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;
}
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
最佳答案
您要查找的是snprintf
:
snprintf(mystring, sizeof mystring, "A%.1fC", b);
关于c - 如何将字符串文字和浮点数混合使用,并在C中将它们连接成一个字符串?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31057490/