A faster approach:
If the maximum amount of padding that you'll ever need is known in advance (which is normally the case when you're formatting a fixed-width table like the one you have), you can use a static "padder" string and just grab a chunk out of it. This will be faster than calling printf
or cout
in a loop.
static const char padder[] = "......................"; // Many chars
size_t title_len = strlen(title);
size_t pad_amount = sizeof(padder) - 1 - title_len;
printf(title); // Output title
if (pad_amount > 0) {
printf(padder + title_len); // Chop!
}
printf("[%d]", data);
You could even do it in one statement, with some leap of faith:
printf("%s%s[%d]", title, padder + strlen(title), data);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…