If I want a program to have multiple text output formats, I could do something like this:
const char *fmtDefault = "%u x %s ($%.2f each)\n";
const char *fmtMultiLine = "Qty: %3u\nItem: %s\nPrice per item: $%.2f\n\n";
const char *fmtCSV = "%u,%s,%.2f\n";
const char *fmt;
switch (which_format) {
case 1: fmt = fmtMultiLine; break;
case 2: fmt = fmtCSV; break;
default: fmt = fmtDefault;
}
printf(fmt, quantity, item_description, price);
Since the price is specified last, I could also add one that doesn't list prices:
const char *fmtNoPrices = "%u x %s\n";
But what if I want to omit the quantity instead? If I did this:
const char *fmtNoQuantity = "The price of %s is $%.2f each.\n";
then undefined behavior (most likely a segfault) will occur rather than what I want. This is because it will treat the first parameter as a pointer to a string, even though it's actually an unsigned int. This unsigned int will most likely point to something other than valid string data, or (much more likely, especially if you're not buying hundreds of millions of the same item) an invalid memory location, resulting in a segmentation fault.
What I want to know is if there's a code I can put somewhere (%Z
in this example) to tell it to skip that parameter, like this:
const char *fmtNoQuantity = "%ZThe price of %s is $%.2f each.";