20
votes

I'm working on a bare-bones Blackjack game that uses sockets, courtesy of my Operating Systems class. We were given a socket interface already which passes an array of characters back and forth.

I had hoped I could do something like this:

char[] msgOut = printf("Dealer's Card is %C %C", char1, char2);
sendMsg(msgOut);

HOWEVER, googling lead me to determine that the return value of printf is an int of the number of Char's output, not a char[] of the chars themselves (as I had hoped).

Is there another C function that lets me build strings from my variables?

3

3 Answers

35
votes

printf writes to standard output. snprintf accomplishes what you are going for here. The interpolated string is stored in 'buffer' after the call to snprintf. You may want define your buffer size a little more intelligently, but this is just an example.

char buffer[1024];
snprintf(buffer, sizeof(buffer), "Dealer's Card is %C %C", char1, char2);
13
votes

Glibc (and several other C libraries) have a convenience function asprintf.

char *msgOut;
asprintf(&msgOut, "Dealer's Card is %C %C", char1, char2);
sendMsg(msgOut);
free(msgOut);

This is most useful when you do not have a good advance prediction for the amount of memory that is required to hold the string. (If you do, snprintf has less overhead, as it does not dynamically allocate memory.)

On systems without asprintf, but with a standards-compliant snprintf, it can be implemented by two calls to snprintf — first with no buffer and zero size to determine the string length, an intervening malloc, and then a second time using that newly allocated space.

2
votes

If you want a string builder in c that dynamically allocates memory I found http://linux.die.net/man/3/vasprintf to be useful.

Example:

#include <stdio.h>

int i;
printf("//Simple dynamic string builder:\n");
char *strs[6] = {"I","am","an","array","of","strings"};

char *buf = "["; // open bracket
for (i=0;i<6;i++) {
    // Dynamically build and allocate memory
    asprintf(&buf,"%s%s",buf,strs[i]);
    if(i!=5) { // Add a comma , after each but skip the last
        asprintf(&buf,"%s,",buf);
    }
}
asprintf(&buf,"%s]",buf); // closing backet
printf("\"%s\"\n",buf);

The output is

//Simple string builder:
"[I,am,an,array,of,strings]"

so char *buf is dynamically being expanded by asprintf and is building by formatting itself into the asprintf statement.