Building a Format String

In the printf() function, the first argument is a format string. It can contain the various percent placeholders to represent values expressed in the remaining arguments. But can one of those arguments also contain placeholders?

The answer is “No.” Only the first argument is scanned for the percent placeholders. So the following trick doesn’t work:

#include <stdio.h>

int main()
{
    printf("My name is %s\n","Dan %s","Gookin");

    return(0);
}

I suppose the logic here is that the second argument, "Dan %s", is somehow combined with the format string to allow access to the third argument. When you compile the code, however, you receive a warning about a surplus argument in the printf() statement. The output looks like this:

My name is Dan %s

Because the first argument to the printf() statement can be a variable, it’s possible to construct the format string on-the-fly to include however many arguments you desire. Such a maneuver is tricky and you must be careful to ensure that the number of placeholders matches the number of arguments lest the program go haywire.

To make it work, employ the string-building function, sprintf(). Concoct the string so that it contains the proper number of placeholders, as is done in the following code:

#include <stdio.h>

int main()
{
    char format0[32];
    char format1[] = "My name is %s";
    char format2[] = " %s\n";

    sprintf(format0,"%s%s",format1,format2);
    printf(format0,"Dan","Gookin");

    return(0);
}

Three character buffers are used in this code: format0[], format1[], and format2[]. The first is storage and the second two are formatting strings.

Line 9 uses the sprintf() function to concatenate format1[] and format[2], placing the result into the format0[] buffer. The result is a formatting string with two %s placeholders. These come from the separate strings. (The "%s%s" formatting string in the sprintf() function is what concatenates the two strings.) Here’s the resulting format string:

"My name is %s %s\n"

This string is used in the printf() statement at Line 10, which then gobbles arguments "Dan" and "Gookin" to create the output:

My name is Dan Gookin

I suppose the point of this Lesson isn’t so much that you cannot create a formatting string by using other arguments in the printf() function, but that a method to accomplish what you need is probably available otherwise. In this example, creating a flexible formatting string is possible, but the entire string must be created first, not within the printf() function itself.

Leave a Reply