围绕与字符串的printf() [英] Centering strings with printf()

查看:122
本文介绍了围绕与字符串的printf()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在默认情况下,的printf()似乎对准字符串的权利。

By default, printf() seems to align strings to the right.

printf("%10s %20s %20s\n", "col1", "col2", "col3");
/*       col1                 col2                 col3 */

我也可以对齐文本这样左:

I can also align text to the left like this:

printf("%-10s %-20s %-20s", "col1", "col2", "col3");

是否有一个快速的方法来居中文本?还是我来写,变成像测试字符串转换成(空间)的函数(空间)的测试(空间)(空间),如果该列的文字宽度为8?

Is there a quick way to center text? Or do I have to write a function that turns a string like test into (space)(space)test(space)(space) if the text width for that column is 8?

推荐答案

的printf本身不能做的伎俩,但你可以用间接的宽度,它通过从参数读取它指定宽度玩。让我们'试试这个(ok了,不完美)

printf by itself can't do the trick, but you could play with the "indirect" width, which specifies the width by reading it from an argument. Lets' try this (ok, not perfect)

void f(char *s)
{
        printf("---%*s%*s---\n",10+strlen(s)/2,s,10-strlen(s)/2,"");
}
int main(int argc, char **argv)
{
        f("uno");
        f("quattro");
        return 0;
}

这篇关于围绕与字符串的printf()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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