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

732 Views Asked by At

I'm a little rusty with C, and I want to concatenate several strings and floats together. In particular, I want to make the string "AbC" where A and C are string literals and b is a float. I understand I must turn the float into a string, but my code is not compiling. Below is my code, followed by the output of gcc. Any suggestions on how to fix my code?

My Program:

#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 Output:

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
3

There are 3 best solutions below

0
On BEST ANSWER

What you are looking for is snprintf:

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

You could replace all of your lines with just:

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

And to be safe (prevent overwritting past the end of your array):

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

There is no ftoa function in the C standard library.

The easiest way to do what you were trying to do, given only the functionality of standard C, is with snprintf:

#include <stdio.h>
int main(void)
{
    double b = 0.5;
    char mystring[16];
    snprintf(mystring, 16, "A%gC", b);
    puts(mystring);
    return 0;
}

If your C library has the nonstandard function asprintf, that frees you from having to figure out how big to make the buffer:

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