zoukankan      html  css  js  c++  java
  • printf格式控制详解

    format 参数输出的格式,定义格式为

    %[flags][width][.precision][length]specifier

    specifier在最后面。定义了数据类型。

    Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:

    specifierOutputExample
    d or i Signed decimal integer 392
    u Unsigned decimal integer 7235
    o Unsigned octal 610
    x Unsigned hexadecimal integer 7fa
    X Unsigned hexadecimal integer (uppercase) 7FA
    f Decimal floating point, lowercase 392.65
    F Decimal floating point, uppercase 392.65
    e Scientific notation (mantissa/exponent), lowercase 3.9265e+2
    E Scientific notation (mantissa/exponent), uppercase 3.9265E+2
    g Use the shortest representation: %e or %f 392.65
    G Use the shortest representation: %E or %F 392.65
    a Hexadecimal floating point, lowercase -0xc.90fep-2
    A Hexadecimal floating point, uppercase -0XC.90FEP-2
    c Character a
    s String of characters sample
    p Pointer address b8000000
    n Nothing printed.
    The corresponding argument must be a pointer to a signed int.
    The number of characters written so far is stored in the pointed location.
     
    % % followed by another % character will write a single % to the stream. %

    问:double如何表示,用%lf。

    The format specifier can also contain sub-specifiers: flagswidth.precision and modifiers (in that order), which are optional and follow these specifications:

    flagsdescription
    - Left-justify within the given field width; Right justification is the default (see width sub-specifier).
    + Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
    (space) If no sign is going to be written, a blank space is inserted before the value.
    # Used with ox or X specifiers the value is preceeded with 00x or 0X respectively for values different than zero.
    Used with aAeEfFg or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
    0 Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).

    -左对齐。右边填充空格。

    在数字前增加符号 + 或 -

    0数字零将输出的前面补上0,直到占满指定列宽为止(不可以搭配使用“-”)

    int a=10;

    printf("%8d ",a);
    printf("%-8d ",a);
    printf("%08d ",a);

    输出:

        10
    10            (左对齐,右边填满空格)
    00000010
    请按任意键继续. . .

    widthdescription
    (number) Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
    * The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
    n(n=1,2,3...) 宽度至少为n位,不够以空格填充。(前面以空格填充)
    0n(n=1,2,3...) 宽度至少为n位,不够左边以0填充。(正如前面所讲,flag=0;输出前面补0)。
     
    * 格式列表中,下一个参数还是width
    .precisiondescription
    .number For integer specifiers (diouxX): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0.
    For aAeEf and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
    For g and G specifiers: This is the maximum number of significant digits to be printed.
    For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered.
    If the period is specified without an explicit value for precision0 is assumed.
    .* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

    对于浮点数而言,m.n宽度为m,精度为n,n表示小数点后还有几位。m指域宽,即对应的输出项在输出设备上所占的字符数(包括小数点)。N指精度。用于说明输出的实型数的小数位数。为指定n时,隐含的精度为n=6位。

    %f:不指定宽度,整数部分全部输出并输出6位小数。
    %m.nf :输出共占m列,其中有n位小数,如数值宽度小于m左端补空格。

    %0m.nf :输出共占m列,其中有n位小数,如数值宽度小于m左端补0。
    %-m.nf:输出共占n列,其中有n位小数,如数值宽度小于m右端补空格。

    float f;
    scanf("%f",&f);
    printf("%f ",f);
    printf("%3.3f ",f);

    输出:

    3.4321
    3.432100
    3.432 (小数点后还有3位)
    请按任意键继续. . .

     上面的%3.3f有点问题,m一般大于n(m包括小数点)。

    float f;
    scanf("%f",&f);
    printf("%f ",f);
    printf("%6.3f ",f);

    输出:

    1.1
    1.100000
     1.100(前面有一个空格,加上小数点,共占6为)。
    请按任意键继续. . .

     "%m.ns":输出m位,取字符串(左起)n位,左补空格,当n>m or m省略时m=n              

          e.g.    "%7.2s"   输入CHINA                                            

                          输出"     CH"    

     "%m.nf":输出浮点数,m为宽度,n为小数点右边数位                  

        e.g.    "%3.1f"    输入3852.99                                

                    输出3853.0        长度:为h短整形量,l为长整形量


    The length sub-specifier modifies the length of the data type. This is a chart showing the types used to interpret the corresponding arguments with and without length specifier (if a different type is used, the proper type promotion or conversion is performed, if allowed):

    数据类型长度修饰符:

     specifiers
    lengthd iu o x Xf F e E g G a Acspn
    (none) int unsigned int double int char* void* int*
    hh signed char unsigned char         signed char*
    h short int unsigned short int         short int*
    l long int unsigned long int   wint_t wchar_t*   long int*
    ll long long int unsigned long long int         long long int*
    j intmax_t uintmax_t         intmax_t*
    z size_t size_t         size_t*
    t ptrdiff_t ptrdiff_t         ptrdiff_t*
    L     long double        

    Note that the c specifier takes an int (or wint_t) as argument, but performs the proper conversion to a charvalue (or a wchar_t) before formatting it for output.

    signed char c;
    scanf("%hhd",&c);
    printf("%c",c);

    输出48,会输出0字符。

    但是运行会错误。stack was corrupted.

    一直很奇怪的hhd问题,vc总是会报错。今天终于找到了答案:原因是VS2010还不支持

    c99的hhd。

    参考这个网页:

    http://connect.microsoft.com/VisualStudio/feedback/details/416843/sscanf-cannot-not-handle-hhd-format



    Note: Yellow rows indicate specifiers and sub-specifiers introduced by C99. See <cinttypes> for the specifiers for extended types.
    ... (additional arguments)Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n).
    There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function.

    返回值:

    On success, the total number of characters written is returned. 如果成功,

    If a writing error occurs, the error indicator (ferror) is set and a negative number is returned.

    If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned.

    /* printf example */
    #include <stdio.h>
    
    int main()
    {
       printf ("Characters: %c %c 
    ", 'a', 65);
       printf ("Decimals: %d %ld
    ", 1977, 650000L);
       printf ("Preceding with blanks: %10d 
    ", 1977);
       printf ("Preceding with zeros: %010d 
    ", 1977);
       printf ("Some different radices: %d %x %o %#x %#o 
    ", 100, 100, 100, 100, 100);
       printf ("floats: %4.2f %+.0e %E 
    ", 3.1416, 3.1416, 3.1416);
       printf ("Width trick: %*d 
    ", 5, 10);
       printf ("%s 
    ", "A string");
       return 0;
    }
    Characters: a A
    Decimals: 1977 650000
    Preceding with blanks:       1977
    Preceding with zeros: 0000001977
    Some different radices: 100 64 144 0x64 0144
    floats: 3.14 +3e+000 3.141600E+000
    Width trick:    10
    A string

    ------------------------------------------------------------------------------

    一篇文章:printf格式。

    printf()函数是格式输出函数,请求printf()打印变量的指令取决与变量的类型.例如,在打印整数是使用%d符号,在打印字符是用%c 符号.这些符号被称为转换说明.因为它们指定了如何不数据转换成可显示的形式.下列列出的是ANSI C标准peintf()提供的各种转换说明.
     
              转换说明及作为结果的打印输出
    %a                浮点数、十六进制数字和p-记数法(C99)
    %A    浮点数、十六进制数字和p-记法(C99)
    %c    一个字符 
    %d    有符号十进制整数 
    %e    浮点数、e-记数法
    %E    浮点数、E-记数法
    %f    浮点数、十进制记数法  
    %g    根据数值不同自动选择%f或%e.
    %G    根据数值不同自动选择%f或%e.
    %i               有符号十进制数(与%d相同)
    %o    无符号八进制整数
    %p    指针    
    %s    字符串
    %u    无符号十进制整数
    %x    使用十六进制数字0f的无符号十六进制整数 
    %X    使用十六进制数字0f的无符号十六进制整数
    %%    打印一个百分号
      使用printf ()函数
     printf()的基本形式: printf("格式控制字符串",变量列表);
     
    #include<cstdio>
    int main()
    {
        //for int
        int i=30122121;
        long i2=309095024l;
        short i3=30;
        unsigned i4=2123453;
        printf("%d,%o,%x,%X,%ld,%hd,%u ",i,i,i,i,i2,i3,i4);//如果是:%l,%h,则输不出结果 
        printf("%d,%ld ",i,i2);//试验不出%ld和%d之间的差别,因为long是4bytes
        printf("%hd,%hd ",i,i3);//试验了%hd和%d之间的差别,因为short是2bytes
    
        //for string and char
        char ch1="d";
        unsigned char ch2=160;
        char *str="Hello everyone!";
        printf("%c,%u,%s ",ch1,ch2,str);//unsigned char超过128的没有字符对应
       
        //for float and double,unsigned and signed can not be used with double and float
        float fl=2.566545445F;//or 2.566545445f
        double dl=265.5651445;
        long double dl2=2.5654441454;
    
        //%g没有e格式,默认6位包括小数点前面的数,
        //%f没有e格式,默认6位仅只小数点后面包含6位
        //%e采用e格式,默认6位为转化后的小数点后面的6位
        printf("%f,%e,%g,%.7f ",fl,dl,dl,dl);
        printf("%f,%E,%G,%f ",fl,dl,dl,dl);//%F is wrong
        printf("%.8f,%.10e ",fl,dl);
        printf("%.8e,%.10f ",fl,dl);
    
        //for point 
        int *iP=&i;
        char *iP1=new char;
        void *iP2;//dangerous!
        printf("%p,%p,%p ",iP,iP1,iP2);
        
        //其他知识:负号,表示左对齐(默认是右对齐);%6.3,6表示宽度,3表示精度
        char *s="Hello world!";
        printf(":%s: :%10s: :%.10s: :%-10s: :%.15s: :%-15s: :%15.10s: :%-15.10s: ",
            s,s,s,s,s,s,s,s);
        double ddd=563.908556444;
        printf(":%g: :%10g: :%.10g: :%-10g: :%.15g: :%-15g: :%15.10g: :%-15.10g: ",
            ddd,ddd,ddd,ddd,ddd,ddd,ddd,ddd);
    
        //还有一个特殊的格式%*.* ,这两个星号的值分别由第二个和第三个参数的值指定
        printf("%.*s ", 8, "abcdefgggggg");
        printf("%*.*f   ", 3,3, 1.25456f);
     
        return 0;
    }
  • 相关阅读:
    CCF NOI1079 合法C标识符
    CCF NOI1080 统计字符
    CCF NOI1076 进制转换
    CCF NOI1065 最小公倍数
    CCF NOI1139 高精度减法
    CCF NOI1138 高精度加法
    CCF NOI1115 找数
    CCF NOI1097 数列
    CCF NOI1089 高精度运算
    NUC1931 Problem D 区间素数【素数筛选】
  • 原文地址:https://www.cnblogs.com/youxin/p/3234472.html
Copyright © 2011-2022 走看看