简体   繁体   中英

How to printf a fixed length output from format

This following code:

printf("%d. %-10s:", 1, "Test");

produces this output:

1. Test      :// 14 characters long

I would like the output length of the entire format `%d. %-10s:" to be exactly 10 characters like this:

1. Test:  // 10 characters

Note:

The numbers vary in length, it could be 1 or 100, so I can't deduce it's length from the output.

How can I do that?

You need to use two steps:

char buffer[20];
snprintf(buffer, sizeof(buffer), "%d. %s:", 1, "Test");
printf("%-*s", 10, buffer);

The snprintf() operation give you a string 1. Test: in buffer ; note that it includes the : in the output, and assumes no trailing blanks on the string "Test" ). The printf() operation formats the string left justified ( - ) in a length of (at least) 10 (the * in the format and the 10 in the argument list) onto standard output. Presumably, something else will appear after this output on the same line; otherwise, there's no obvious point to the blank padding.

For full information, see:

This covers the basic operation of the *printf() family of functions (but does not list the interfaces to the v*printf() or *wprintf() families of functions).

The code in the question and in the answer above is all done with constants. A more realistic scenario would be:

void format_item(int number, const char *text, int width)
{
    char buffer[width+1];  // C99 VLA
    snprintf(buffer, sizeof(buffer), "%d. %s:", number, text);
    printf("%-*s", width, buffer);
}

Note that this code truncates the formatted data if the number plus the string is too long. There are ways around that if you work a bit harder (like adding more than 1 to width in the definition of buffer — maybe add 15 instead of 1).

You might write:

format_item(1, "Test", 10);

or:

char *str_var = …some function call, perhaps…
int item = 56;
format_item(++item, str_var, 20);

etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM