美文网首页
printf限制字符串长度

printf限制字符串长度

作者: 一路向后 | 来源:发表于2020-11-11 21:29 被阅读0次

1.程序源码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
        //原样输出字符串
        printf("%s\n", "543");

        //输出指定长度的字符串, 超长时不截断, 不足时右对齐
        printf("%5s\n", "543");
        printf("%5s\n", "543210");

        //输出指定长度的字符串, 超长时不截断, 不足时左对齐
        printf("%-5s\n", "543");
        printf("%-5s\n", "543210");

        //输出指定长度的字符串, 超长时截断, 不足时右对齐
        printf("%5.3s\n", "54");
        printf("%5.3s\n", "5432");
        printf("%5.3s\n", "543210");

        //输出指定长度的字符串, 超长时截断, 不足时左对齐
        printf("%-5.3s\n", "54");
        printf("%-5.3s\n", "5432");
        printf("%-5.3s\n", "543210");

        //输出不定长字符串, 超长时截断
        printf("%.5s\n", "543");
        printf("%.5s\n", "543210");

        return 0;
}

2.编译程序

$ gcc -o example example.c

3.运行结果

$ ./example
543
  543
543210
543  
543210
   54
  543
  543
54   
543  
543  
543
54321

相关文章

网友评论

      本文标题:printf限制字符串长度

      本文链接:https://www.haomeiwen.com/subject/gimybktx.html