带空格的左pad printf [英] Left-pad printf with spaces

查看:18
本文介绍了带空格的左pad printf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 printf 时如何在左侧填充空格?

How can I pad a string with spaces on the left when using printf?

例如,我想打印前面有 40 个空格的Hello".

For example, I want to print "Hello" with 40 spaces preceding it.

另外,我要打印的字符串由多行组成.我需要单独打印每一行吗?

Also, the string I want to print consists of multiple lines. Do I need to print each line separately?

为了清楚起见,我希望在每行之前打印 40 个空格.

Just to be clear, I want exactly 40 spaces printed before every line.

推荐答案

如果您希望单词Hello"打印在 40 个字符宽的列中,并在左侧填充空格,请使用以下内容.

If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.

char *ptr = "Hello";
printf("%40s
", ptr);

这将给你 35 个空格,然后是你好"这个词.当您知道想要列的宽度时,这就是您格式化内容的方式,但数据会发生变化(嗯,这是您可以做到的一种方式).

That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).

如果您知道您需要 40 个空格然后是一些文本,只需将 40 个空格保存在一个常量中并打印它们.如果您需要打印多行,可以使用多个 printf 语句,如上面的语句,或者循环执行,每次更改 ptr 的值.

If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf statements like the one above, or do it in a loop, changing the value of ptr each time.

这篇关于带空格的左pad printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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