简体   繁体   English

如何从格式打印固定长度的输出

[英]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. 我想要整个格式`%d的输出长度。 %-10s:" to be exactly 10 characters like this: %-10s:“正好是这样的10个字符:

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. 数字长度不一,可能是1或100,所以我无法从输出中推断它的长度。

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 ; snprintf()操作给你一个字符串1. Test:buffer ; note that it includes the : in the output, and assumes no trailing blanks on the string "Test" ). 请注意,它包含:在输出中,并假定字符串"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. printf()操作将字符串左对齐( - )格式化为(至少)10(格式中的*和参数列表中的10)的长度到标准输出。 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). 这包括*printf()系列函数的基本操作(但不列出v*printf()*wprintf()函数族的接口)。

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). 如果你的工作有点困难(比如在buffer的定义中添加超过1width - 可能会增加15而不是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. 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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