c - 在 C 中使用 printf 或 printstring 格式化文本

标签 c

我想从微 Controller 将文本打印到终端程序,如下所示:

printString("textline one here:            OK\n");
printString("textline two here that is longer:             OK\n");
printString("textline three here that is even  longer:             OK\n");

即使我决定更改文本行,如何使文本始终位于列中?为了避免这种情况,它在终端程序的打印输出中看起来像这样:

textline one here:             OK
textline two here that is longer:              OK
textline three here that is even  longer:              OK

以及更多类似的内容(无需在文本中添加额外的空格并在终端程序中仔细检查我对任何文本所做的每个更改的外观):

textline one here:                             OK
textline two here that is longer:              OK
textline three here that is even  longer:      OK

使用 printf 或 printstring 更容易吗?

最佳答案

不要将文本的第一部分直接包含在 printf 格式字符串中,而是将其作为参数传递给 %s 格式说明符。然后,您可以向其添加字段宽度以指定要打印的最小字符数以及 - 标志以告诉其左对齐。

例如,这段代码:

printf("%-50s %s\n", "textline one here:", "OK");
printf("%-50s %s\n", "textline two here that is longer:", "OK");
printf("%-50s %s\n", "textline three here that is even  longer:","OK");

打印:

textline one here:                                 OK
textline two here that is longer:                  OK
textline three here that is even  longer:          OK

此外,您可以使用 * 而不是显式字段宽度将其作为参数传递。这样,如果您需要更改列宽,您只需在一处进行即可:

int width = 50;
printf("%-*s %s\n", width, "textline one here:", "OK");
printf("%-*s %s\n", width, "textline two here that is longer:", "OK");
printf("%-*s %s\n", width, "textline three here that is even  longer:","OK");

关于c - 在 C 中使用 printf 或 printstring 格式化文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59756396/

相关文章:

c - 将 bool 数组的最后一个元素设置为位字段中的最高有效位

c - 用于计算整数中 1 位的递归程序

c - 子 PID 的执行和打印

c - OpenMP 和私有(private)可重用内存

c - 不知道在多线程的情况下如何从终端获取命令

c - 可比性测试比%运算符更快?

java - java中有没有一种setjmp/longjmp?

c - 如何知道应用程序在运行时链接了哪个?

c - 如何同时应用多个过滤器?

java - 快速提问(尝试看看我是否明白如何做到这一点)