我想从微 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/