Building Strings from variables in C

64,554

Solution 1

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

Solution 2

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.

Solution 3

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.

Share:
64,554
Raven Dreamer
Author by

Raven Dreamer

Follow my hobby development at: https://storm-shark.itch.io/

Updated on December 16, 2020

Comments

  • Raven Dreamer
    Raven Dreamer over 3 years

    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?

  • Ed S.
    Ed S. over 13 years
    No, look at the example. The buffer will be modified in place. Many functions in C return error codes and modify their arguments in place. You'll have to get used to this writing code in C.
  • Raven Dreamer
    Raven Dreamer over 13 years
    Yes. Shortsightedness on my part. I reread your answer moments after writing that comment.
  • arunmoezhi
    arunmoezhi about 10 years
    @EdS.: How do you append to buffer. Say I want to invoke snprintf on buffer multiple times, but don't want text inside buffer to get overwritten.
  • Ed S.
    Ed S. about 10 years
    @arunmoezhi: Pass in a pointer to some offset within the buffer, i.e., buffer + n, sizeof(buffer) - n.
  • arunmoezhi
    arunmoezhi about 10 years
    @EdS.: And I should increment n after each call?
  • Ed S.
    Ed S. about 10 years
    @arunmoezhi: n is just the offset, it's whatever you need it to be.
  • Reuel Ribeiro
    Reuel Ribeiro almost 8 years
    Just attend to the fact that asprintf is a GNU extension, and not a C/POSIX de facto method.
  • David Callanan
    David Callanan over 6 years
    @arunmoezhi If your first call to snprintf adds 5 characters to your buffer then the total length of the string is 5, so that will be your offset n. Of course you may not know this number, and you can call strlen(buffer) to obtain this. Remember to #include <string.h> or <cstring> if you are doing this. Also remember to make sure the buffer is large enough to hold all the data you will be adding, otherwise you may need to dynamically allocate memory or increase the size of the buffer.
  • Jman
    Jman about 5 years
    Awesome! Quick answer that fixed an issue I had been struggling with all morning!