printf a Limited Number of Characters from a String

I learned recently that you can control the number of characters that printf will show for a string using a precision specifier (assuming your printf implementation supports this).

There are two ways to approach string-limiting. The first method specifies the number of characters to print inside the format string itself:

// Only 5 characters printed
const char * mystr = "This string is definitely longer than what we want to print.";
printf("Here are first 5 chars only: %.5s\n", mystr);

Note the .5 that is included in the %s symbol: that tells printf to print a maximum of five characters (NULL termination is still valid).

However, you can also control this programmatically, which is useful if the length you want to print is tracked in a variable:

// Only 5 characters printed. When using %.*s, add a value before your string variable to specify the length.
printf("Here are the first 5 characters: %.*s\n", 5, mystr); //5 here refers to # of characters

Using * as the precision specifier tells printf that the precision will be provided as a function argument. Simply place your size limit before the string you want to print.

I don't frequently need this support, but I was dealing with a buffer that was not NULL-terminated, and I didn't want printf walking off the map when printing the data. Perhaps you'll end up in a similar situation some day!

Further Reading