Search code examples
cconcatenationcoercion

Concatenate a string like in printf


printf is beautiful function because it helps you formatting your string in a very clean way.

printf("Player %s has lost %d hitpoints", victim.name, damage);

Is there a similar way to concatenate and perform coercion in a "normal string" like below:

uint8_t myString = ("Player %s has lost %d hitpoints", victim.name, damage); //SOMETHING LIKE THIS

Solution

  • C99's snprintf prints to a string and guarantees not to overflow the buffer:

    char msg[48];
    
    snprintf(msg, sizeof(msg),
        "Player %s has lost %d hitpoints", victim.name, damage);
    

    snprintf returns the number of characters that would have been written had the string been large enough. So if the returned values is equal to or larger than the buffer size, the string was truncated.

    It is legal to pass a buffer size of zero and a null pointer, so that you can do your own allocation by making a probing call first:

    char *msg;
    int n;
    
    n = snprintf(NULL, 0,
        "Player %s has lost %d hitpoints", victim.name, damage);
    
    msg = malloc(n + 1);
    n = snprintf(msg, n + 1,
        "Player %s has lost %d hitpoints", victim.name, damage);
    
    // do stuff with msg
    
    free(msg);
    

    On GNU compilers, the non-sandard function asprintf will do that for you:

    char *msg = asprintf("Player %s has lost %d hitpoints",
        victim.name, damage);
    
    // do stuff with msg
    
    free(msg);