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

How do I take a mixture of string literals and floats and concatenate them into one string in C?

我对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

您可以将所有行替换为:

sprintf(mystring, "A%gC", b);

为了安全起见(防止覆盖数组末尾):

snprintf(mystring, sizeof(mystring), "A%gC", b);

您要找的是snprintf

snprintf(mystring, sizeof mystring, "A%.1fC", b);

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;
}