Is there a “null” printf code that doesn't print anything, used to skip a parameter?

微笑、不失礼 提交于 2019-12-05 05:44:14

For %s values, there is a “null” printf() code: %.0s.

You could reach a general solution via:

When possible, re-arrange so that non-%s values are last, and then under specify the format string.

My favorite for you is to have 3 separate printf() calls, one for each value using its own format. When the value is not needed, simply supply a format string with no specifiers.

const char * Format1q   = "";
const char * Format1id  = "The price of %s";
const char * Format1p   = " is $%.2f each.\n";
...
printf(Format1q,  quantity); 
printf(Format1id, item_description);
printf(Format1p,  price);

Weird solutions:

For other values that are the same size you could attempt the Undefined Behavior of also using %.0s. (worked with some samples in gcc 4.5.3, who knows in other compilers or the future.)

For other values that are the N x the same size as a pointer size you could attempt the Undefined Behavior of also using %.0s N times. (worked with some samples in gcc 4.5.3, who knows in other compilers or the future.)

flarn2006

I actually figured this out on my own while looking something up for my question. You can prepend a parameter number, followed by a $ to the format code, after the %. So it would be like this:

const char *fmtNoQuantity = "The price of %2$s is $%3$.2f each.";

That is, the string would use the 2nd parameter, and the float would use the 3rd parameter. Note, however, that this is a POSIX extension, not a standard feature of C.

A better method would probably be to define a custom printing function. Something like this:


typedef enum {fmtDefault, fmtMultiLine, fmtCSV, fmtNoPrices, fmtNoQuantity} fmt_id;

void print_record(fmt_id fmt, unsigned int qty, const char *item, float price)
{
    switch (fmt) {
    case fmtMultiLine:
        printf("Qty: %3u\n", qty);
        printf("Item: %s\n", item);
        printf("Price per item: $%.2f\n\n", price);
        break;
    case fmtCSV:
        printf("%u,%s,%.2f\n", qty, item, price);
        break;
    case fmtNoPrices:
        printf("%u x %s\n", qty, item);
        break;
    case fmtNoQuantity:
        printf("The price of %s is $%.2f each.\n", item, price);
        break;
    default:
        printf("%u x %s ($%.2f each)\n", qty, item, price);
        break;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!