如何使用 printf() 格式化字符串以在输出中获得相等的长度 [英] How to format strings using printf() to get equal length in the output

查看:58
本文介绍了如何使用 printf() 格式化字符串以在输出中获得相等的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个函数,一个函数产生像 Starting initialization... 这样的消息,另一个函数检查返回码并输出 "Ok", "警告"错误".但是,产生的输出长度不同:

I have two functions, one which produces messages like Starting initialization... and another which checks return codes and outputs "Ok", "Warning" or "Error". However, the output that is produced is of the different length:

Starting initialization...Ok.
Checking init scripts...Ok.

我怎样才能得到如下内容?

How can I get something like the following?

Starting initialization...       Ok.
Checking init scripts...         Ok.

推荐答案

您可以在字符串字段上指定宽度,例如

You can specify a width on string fields, e.g.

printf("%-20s", "initialization...");

然后用该字段打印的任何内容都将空白填充到您指定的宽度.

And then whatever's printed with that field will be blank-padded to the width you indicate.

- 在该字段中左对齐您的文本.

The - left-justifies your text in that field.

这篇关于如何使用 printf() 格式化字符串以在输出中获得相等的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆