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

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

问题描述

我怎么能垫左侧空间用printf当一个字符串?

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

例如,我想打印你好与40位preceding它。

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.

推荐答案

如果您想要的单词你好,以一列那是宽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\n", 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.

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

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