printf 字符串输出固定长度

来源:互联网 发布:阿里云邮件 编辑:程序博客网 时间:2024/04/30 17:05

#include <stdio.h>

void main()
{
   char str[20] = "abcdefg";
    double n = 10.1234567;
 printf("%.3s /n", str);
 printf("%.3f /n", n);
}

 

输出:abc
          10.123

下面对printf中的%.M输出做一下简单的分析,在printf的定义中,回解析所有的字符有自己的协议栈来分析format的参数,其中,

/* 一下内容来自output.c-------------------------------------------------------

 while ((ch = *format++) != _T('/0') && charsout >= 0) {
        chclass = find_char_class(ch);  /* find character class */
        state = find_next_state(chclass, state); /* find next state */
      /* execute code for each state */
        switch (state) {
......
                case ST_DOT:
            /* zero the precision, since dot with no number means 0
               not default, according to ANSI */
            precision = 0;
            break;

--------------------------------------------------------------*/

就如代码中所说的,如果小数点后面不是数字,则按照ANSI标准来格式化后面的输出,来比较输出的长度

原创粉丝点击