sprintf的三个要点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ssss1223ss/article/details/59134102

函数原型:int sprintf(const char *fmt, …),其中fmt格式为:%[width][.prec][type]


width之误解

width为字符的最小长度,如果不够,默认以空格右补齐。很多人误以为是最大长度限制,写出内存写越界的bug。

比如:

    char  buf[3];
    unsigned c = -1;
    sprintf(buf, "%3u", c);

当使用%s格式化字符串时,[.prec]可以截取控制字符串的长度

比如:

    printf("%.3s", "123456789");

输出结果:123


[width][.prec]均可用*代替,在参数列表指定数值。

比如:

    printf("%-*s%.*s\n", 5,  "abcd", 3, "123456789");

输出结果:abcd 123

猜你喜欢

转载自blog.csdn.net/ssss1223ss/article/details/59134102