我对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
答案 0 :(得分:5)
您要找的是snprintf
:
snprintf(mystring, sizeof mystring, "A%.1fC", b);
答案 1 :(得分:4)
您可以只用以下内容替换所有行:
sprintf(mystring, "A%gC", b);
为了安全起见(防止覆盖数组的末尾):
snprintf(mystring, sizeof(mystring), "A%gC", b);
答案 2 :(得分:2)
C标准库中没有ftoa
函数。
仅使用标准C的功能,最简单的方法是执行您尝试执行的操作,使用snprintf
:
#include <stdio.h>
int main(void)
{
double b = 0.5;
char mystring[16];
snprintf(mystring, 16, "A%gC", b);
puts(mystring);
return 0;
}
如果您的C库具有非标准函数asprintf
,那么您将无需弄清楚缓冲区的大小:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
double b = 0.5;
char *mystring = 0;
if (asprintf(&mystring, "A%gC", b) == -1)
{
perror("asprintf");
return 1;
}
puts(mystring);
free(mystring);
return 0;
}