Make a New String On-The-Fly

Never underestimate the power of the printf() function. It has amazing abilities to format output. And don’t forget about printf()‘s lesser-known cousin, sprintf(). It can do amazing things with strings.

The sprintf() function is nearly identical to printf(). It uses the same formatting power. The difference lies in where the string ends up: For printf(), the formatted string is sent to standard output. For sprintf(), however, the formatted string is saved to a character array (buffer) in memory. That’s powerful.

The printf() function has this format:

printf("format"[,args...]);

format is the formatting string, or a string variable; args are the optional arguments, values or variables, one for each conversion character in the format string. You’re probably quite familiar with this format.

The sprintf() function uses a similar format to printf():

sprintf(char *buffer,"format"[,args...]);

The difference between printf() and sprintf()‘s arguments is addition of a char buffer. That’s the address of the string created. So instead of being sent to standard output, the formatted string is saved to a location in memory.

Here’s a quick example:

#include <stdio.h>

int main()
{
    char string[3];

    sprintf(string,"%d",15*5);
    printf("15 * 5 = ");
    puts(string);

    return(0);
}

The buffer string at Line 5 has room for two characters, plus one character for the \0 (null) at the end of the string. Remember that!

The sprintf() function at Line 7 calculates the result of 15 times 5, formats it as an integer by using %d, and saves the output in the string buffer. Lines 8 and 9 display the result.

On your own, modify the code so that the entire string is formatted and saved to the string buffer and then output using a puts() function. Click here to see my solution.

The sprintf() function has lots of potential for building strings in memory. It can be used to convert numbers into strings, building strings with numbers, and even manipulate strings. It’s pretty powerful.

For example, you could have use the sprintf() function as a solution for the October 2013 Exercise on this blog.

October’s puzzle was to insert the text , nastiest into the string That's the biggest spider I've ever seen! Here’s one way that task could be accomplished by using the sprintf() function:

#include <stdio.h>

int main()
{
    char *text = "That's the biggest spider I've ever seen!";
    char *insert = ", nastiest";
    char buffer[52];

    sprintf(buffer,"%.18s%s%s",text,insert,text+18);
    puts(buffer);

    return(0);
}

Here’s the output:

That's the biggest, nastiest spider I've ever seen!

Yes, I cheated in the code by directly specifying the value 18 and the buffer size of 52. In a “real” program, you would want to calculate the values, but then the solution would be more along the lines of what’s presented for the October 13 exercise. My point here is to demonstrate the power of sprintf().

Leave a Reply