Conversion Character Mania: Text Output

The printf() function’s conversion characters %s and %c seem to be rather straightforward. Or are they?

First the easy one: To output a single character of text, use %c. That conversion character has no options, settings, or optional detritus that can be wedged between the % and the c. Simple.

The %s conversion character displays strings of text. The entire string is displayed, from the start to the character before the terminating null, character \0. That’s how %s is used most often, but it’s not the limits of how you can format a string of text for output.

#include <stdio.h>

int main()
{
    char string[] = "spatula";

    printf("%s\n",string);
    printf("%12s\n",string);
    printf("%-12s\n",string);
    printf("%12.3s\n",string);
    printf("%-12.3s\n",string);

    return(0);
}

If you’ve messed with the %s conversion character (as shown in my books), then you probably have used some of the examples shown in the above code. Most frequently, %12s and %-12s. Both limit output to a span of 12 characters; the - sign left-justifies the output. These are the same width and alignment options available for formatting numeric output.

What may seem odd to you is the .3 option. That’s the precision setting, which has a unique effect on strings. Here’s the program’s output:

spatula
     spatula
spatula     
         spa
spa        

In the first line %s outputs the entire string.

The second uses %12s to right-justify the output within a width of 12 characters. As with numeric output, if the string is longer than 12 characters, the entire string is displayed; no justification.

The third example uses %-12s to left-justify output within a width of 12 characters. When the string is longer than the width value, no justification is used.

The fourth and fifth examples add a period and a second value, .3. The effect this “precision” value is to truncate the entire string to the number of characters specified.

So the conversion character %12.3s sets output to a 12 character width and truncates output to only the first three characters of the string. The output is right-justified:

         spa

The conversion character %-12.3s sets output to a 12 character width, left-justified, and truncates the string to the first 3 characters:

spa

The truncating doesn’t affect the string itself, only the output.

Unlike numeric conversion characters, the + and 0 prefix before the width value aren’t allowed for %s. If you want that sort of output, you’ll have to code it yourself.

Next lesson I wrap up my Conversion Character Mania series with the rest of the lot not yet covered.

Leave a Reply