zoukankan      html  css  js  c++  java
  • sprintf用法

    sprintf(string,"%f",num);
    string是一个字符串,num是你要的数字,这样就能将浮点数num转成字符串string了,你那个写法是错的,后面还有对指针进行运算也是不对的。

    char s[20];
    int a=10;
    sprintf(s,"%d.jpg",a);
    //若a=10,则字符串s中存放的是"10.jpg".

    C语言在字符串处理中本来就很繁琐,但字符串处理是编写代码最常遇到的问题,今天说的sprintf是printf的加强版。用好了它

    能在字符串处理中做到事半功倍的效果,具体看代码:

    函数简介:

    字串格式化命令,主要功能是把格式化的数据写入某个字符串中。sprintf 是个变参函数,使用时经常出问题,而且只要出问题通常就是能导致程序崩溃的内存访问错误,但好在由sprintf 误用导致的问题虽然严重,却很容易找出,无非就是那么几种情况,通常用眼睛再把出错的代码多看几眼就看出来了。

    函数功能:

      把格式化的数据写入某个字符串缓冲区。

    头文件:

      stdio.h

    函数原型:

      int sprintf( char *buffer, const char *format, [ argument] … );

    参数列表:

      buffer:char型指针,指向将要写入的字符串的缓冲区。

      format:char型指针,指向的内存里面存放的将要格式字符串。

      [argument]...:可选参数,可以是任何类型的数据。

      返回值:字符串长度(strlen)

    相关函数:

      int sprintf_s(char *buffer,size_t sizeOfBuffer,const char *format, [argument] ... );

      int _sprintf_s_l(char *buffer,size_t sizeOfBuffer,const char *format,locale_t locale ,[argument] ... );

      int swprintf_s(wchar_t *buffer,size_t sizeOfBuffer,const wchar_t *format ,[argument]...);

      int _swprintf_s_l(wchar_t *buffer,size_t sizeOfBuffer,const wchar_t *format,locale_t locale ,[argument]…);

      template <size_t size>

      int sprintf_s(char (&buffer)[size],const char *format, [argument] ... ); //仅存在于C++

      template <size_t size>

            int swprintf_s(wchar_t (&buffer)[size],const wchar_t *format ,[argument]...); //仅存在于C++

    参数说明及应用举例

      sprintf格式的规格如下所示。[]中的部分是可选的。

      %[指定参数][标识符][宽度][.精度]指示符

      若想输出`%'本身时, 请这样`%%'处理。

      1. 处理字符方向。负号时表示从后向前处理。

      2. 填空字元。 0 的话表示空格填 0;空格是内定值,表示空格就放着。

      3. 字符总宽度。为最小宽度。

      4. 精确度。指在小数点后的浮点数位数。

      =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

    转换字符

      =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

      %% 印出百分比符号,不转换。

      %c 整数转成对应的 ASCII 字元。

      %d 整数转成十进位。

      %f 倍精确度数字转成浮点数。

      %o 整数转成八进位。

      %s 整数转成字符串。

      %x 整数转成小写十六进位。

      %X 整数转成大写十六进位。

    [cpp] view plain copy
     
    1. #include <stdio.h>  
    2. #include <string.h>  
    3. int main()  
    4. {  
    5.     char buf[100] = "";  
    6.   
    7.     //一、整型格式化为字符串(大多数情况下可以由itoa代替)  
    8.     sprintf(buf, "%d", 123);  
    9.     puts(buf);  
    10.     /*output: 123*/  
    11.       
    12.     //指定宽度,不足的左边补空格  
    13.     strcpy(buf, "");  
    14.     sprintf(buf,"%8d%8d", 12,78995);  
    15.     puts(buf);  
    16.     /*output:      12   78995("12"前面有6个空格,"78995"前边3个空格)*/  
    17.       
    18.     //十进制左边对齐输出  
    19.     strcpy(buf, "");  
    20.     sprintf(buf, "%-8d%-8d", 456, 84569);  
    21.     puts(buf);  
    22.     /*output:456     84569(中间5个空格)*/  
    23.       
    24.     //按照16进制打印  
    25.     strcpy(buf, "");  
    26.     sprintf(buf, "%8x", 4578);  
    27.     puts(buf);  
    28.     /*output: 12e2*/  
    29.       
    30.       
    31.     //按照16进制左边补零输出  
    32.     strcpy(buf, "");  
    33.     sprintf(buf, "%08X", 4569);  
    34.     puts(buf);  
    35.     /*output: 000011D9*/  
    36.       
    37.     //左边补零方式打印一个短整型  
    38.     strcpy(buf, "");  
    39.     sprintf(buf, "%04X", (unsigned short)2);  
    40.     puts(buf);  
    41.     /*output: 0002*/  
    42.       
    43.     //二、浮点型打印成字符串  
    44.     strcpy(buf, "");  
    45.     sprintf(buf, "%f", 3.1415926);  
    46.     puts(buf);  
    47.     /*output: 3.141593 四舍五入*/  
    48.       
    49.     //控制宽度和小数点位数输出  
    50.     strcpy(buf, "");  
    51.     sprintf(buf, "%10.3f", 3.1415926);  
    52.     puts(buf);  
    53.     /*output:     3.142(前面5个空格)*/  
    54.       
    55.     //连接字符串  
    56.     strcpy(buf, "");  
    57.     char buf1[]="I"; char buf2[]="you!";  
    58.     sprintf(buf, "%s love %s", buf1, buf2);  
    59.     puts(buf);  
    60.     /*output: I love you!*/  
    61.       
    62.     //连接2个字符串没有以''结束  
    63.     //sprintf 采用”*”来占用一个本来需要一个指定宽度或精度的常数数字的位置  
    64.     strcpy(buf, "");  
    65.     char a1[] = {'a', 'b', 'c', 'd', 'e'};  
    66.     char a2[] = {'f', 'g', 'h', 'j'};  
    67.     //sprintf(buf, "%s%s", a1, a2);                 //error  
    68.     //sprintf(buf, "%5s%4s", a1, a2);               //error  
    69.     //sprintf(buf, "%.5s%.4s", a1, a2);             //method one  
    70.     //sprintf(buf, "%.*s%.*s", 5, a1, 4, a2);       //method two  
    71.     sprintf(buf, "%.*s%.*s", sizeof(a1), a1, sizeof(a2), a2); //method three  
    72.     puts(buf);  
    73.       
    74.     return 0;  
    75. }

    头文件:#include <stdio.h>

    sprintf()函数用于将格式化的数据写入字符串,其原型为:
        int sprintf(char *str, char * format [, argument, ...]);

    【参数】str为要写入的字符串;format为格式化字符串,与printf()函数相同;argument为变量。

    除了前两个参数类型固定外,后面可以接任意多个参数。而它的精华,显然就在第二个参数--格式化字符串--上。 printf()和sprintf()都使用格式化字符串来指定串的格式,在格式串内部使用一些以“%”开头的格式说明符(format specifications)来占据一个位置,在后边的变参列表中提供相应的变量,最终函数就会用相应位置的变量来替代那个说明符,产生一个调用者想要的字符串。

    sprintf()最常见的应用之一莫过于把整数打印到字符串中,如:
        sprintf(s, "%d", 123);  //把整数123打印成一个字符串保存在s中
        sprintf(s, "%8x", 4567);  //小写16进制,宽度占8个位置,右对齐

    sprintf的作用是将一个格式化的字符串输出到一个目的字符串中,而printf是将一个格式化的字符串输出到屏幕。sprintf的第一个参数应该是目的字符串,如果不指定这个参数,执行过程中出现 "该程序产生非法操作,即将被关闭...."的提示。

    sprintf()会根据参数format 字符串来转换并格式化数据,然后将结果复制到参数str 所指的字符串数组,直到出现字符串结束('')为止。关于参数format 字符串的格式请参考printf()。

    【返回值】成功则返回参数str 字符串长度,失败则返回-1,错误原因存于errno 中。

    注意:C语言对数组进行操作时并不检测数组的长度,如果str的长度不够,sprintf()很容易造成缓冲区溢出,带来意想不到的后果,黑客经常利用这个弱点攻击看上去安全的系统。请看下面的代码:

    1. #include <stdio.h>
    2. main()
    3. {
    4. char buf[10];
    5. sprintf(buf, "The length of the string is more than 10");
    6. printf("%s", buf);
    7. }

    编译并运行,屏幕上输出”The length of the string is more than 10“,同时系统提示程序已经停止。原因就是要写入的字符串的长度超过了buf的长度,造成缓冲区溢出。

    使用snprintf()来代替sprintf()将能够很好的解决这个问题。

    【实例】打印字母a的ASCII值。

    1. #include <stdio.h>
    2. main()
    3. {
    4. char a = 'a';
    5. char buf[80];
    6. sprintf(buf, "The ASCII code of a is %d.", a);
    7. printf("%s", buf);
    8. }

    运行结果:
    The ASCII code of a is 97.

    又如,产生10个100以内的随机数并输出。

    1. #include<stdio.h>
    2. #include<stdlib.h>
    3. #include<time.h>
    4. int main(void)
    5. {
    6. char str[100];
    7. int offset =0;
    8. int i=0;
    9. srand(time(0)); // *随机种子
    10. for(i = 0;i<10;i++)
    11. {
    12. offset+=sprintf(str+offset,"%d,",rand()%100); // 格式化的数据写入字符串
    13. }
    14. str[offset-1]=' ';
    15. printf(str);
    16. return 0;
    17. }

    运行结果:
    74,43,95,95,44,90,70,23,66,84

    例子使用了一个新函数srand(),它能产生随机数。例子中最复杂的部分是for循环中每次调用函数sprintf()往字符数组写数据的时候,str+foffset为每次写入数据的开始地址,最终的结果是所有产生的随机数据都被以整数的形式存入数组中。

     

     

    sprintf

    Converts floats or doubles into formatted strings.

    Prototype

    	function sprintf (
    		format [1] : string,  
    		array      : float    ; or double
    	)
    
    	return_val [dimsizes(array)] :  string
    

    Arguments

    format

    A "C" style format string, See "man sprintf" for more information.

    array

    An array of any dimensionality of float or double values.

    Description

    This function uses the format string to call the system "sprintf" function. This is different from the C version in two ways: 1) only one "%" operator is allowed for the string, and 2) only floating point numbers (float and double) are allowed. You must understand how to create a C format string to use this function.

    Briefly, the applicable conversion characters for printing are:

    1. Each conversion specification begins with a % and ends with a conversion character: f, e/E, g/G.
    2. Between the % and the conversion character, there may be, in order:
      • A minus sign, which specifies left adjustment of the converted argument.
      • A number that specifies the minimum field width. The converted argument will be printed in a field at least this wide. It will be padded if necessary.
      • A period, which separates the field width from the precision.
      • A number, the precision, that specifies the maximum number of characters to be printed from a string, or the number of digits after the decimal point of a floating point value.
    3. Conversion characters are:
      f: [-]m.dddddd, where the number of d's is given by the precision (default 6).

      e[,E]: [-]m.dddddde±xx or [-]m.ddddddE±xx, where the number of d's is given by the precision (default 6).

      g[,G]: use %e or %E if the exponent is less than -4 or greater than or equal to the precision; otherwise use %f.

    See Also

    sprintiwrite_matrix

    Examples

    Example 1

    The code snippet:

      x = 12.3456
      title = "Sample title,  x=" + sprintf("%5.2f", x)
    

    will result in title = "Sample title, x=12.35". Note that the value returned by sprintf is rounded, due to the specified print format.

    Example 2

    Here are some additional examples demonstrating the "e[,E]" and "g[,G]" formats:

      x = 12.3456
      print( sprintf("%7.3e", x) )   ===>    1.235e+01
    
      x = -0.000013583 
      print( sprintf("%4.3E", x) )   ===>    -1.358E-05
    
      x = 23456789.
      print( sprintf("%6.4g", x) )   ===>    2.3457e+07
    
      print( sprintf("%6.4G", 10000000.) )   ===>    1E+07
    
      print( sprintf("%6.4g", 10.) )   ===>    10
    
      print( sprintf("%6.4g", 10.56) )   ===>    10.56
    

    Example 3

    A user could also put the format into a string variable:

      fmt = "%5.2f"
      emt = "%7.3e"
      gmt = "%4.3g"
      title = "Sample title,  x=" + sprintf(fmt, x) +" y="+ sprintf(fmt, y) 
                           +" z=" + sprintf(gmt, z)
      subTitle = sprintf(gmt, x)
    

    Example 4

    sprinti and sprintf can be used to provide limited formatting for printing ASCII text. The following code:

      print("      K     mylats      mylons     exacts    mytemps       fo")
      do n=0,N-1
        print (sprinti("%6.0i", knt(n))    +" " 
              +sprintf("%9.5f", mylats(n)) +"  " 
              +sprintf("%9.2f", mylons(n)) +"  " 
              +sprintf("%9.3f", exacts(n)) +"  " 
              +sprintf("%9.4f", mytemps(n))+"  " 
              +sprintf("%9.4f", fo(n))    )
      end do
    

    will produce the following output:

    (0)          K    mylats     mylons     exacts    mytemps       fo
    (0)             16.28100    -126.14     20.650    20.6500    20.6500
    (0)          5  16.28110    -126.14     20.650    20.6500  -999.0000
    (0)         25  16.36279    -125.77     20.550    20.5500    20.5500
    (0)         50  16.36289    -125.77     20.550    20.4501    20.4501
    (0)         75  16.71504    -125.86     20.350    20.3500    20.3500
    (0)        100  16.71514    -125.86     20.350    20.3501    20.3502
    (0)        300  16.63296    -126.22     20.650    20.6500    20.6500
    (0)        400  16.63305    -126.22     20.650    20.6500  -999.0000
    (0)        700  40.57919     -74.57      2.350     2.3500     2.3500
    (0)        900  40.57929     -74.57      2.350     3.4908     3.4891
    (0)       1000  40.52584     -74.11      4.750     4.7500     4.7500
    (0)       3000  40.52594     -74.11      4.750     4.5151     4.5153
    (0)       7000  40.87282     -74.04      1.350     1.3500     1.3500
    (0)      10000  40.87292     -74.04      1.350     2.2145     2.2143
    (0)      15000  40.92625     -74.50      0.850     0.8500     0.8500
    (0)     123456  40.92635     -74.50      0.850     1.4571     1.4570
    
  • 相关阅读:
    [WCF权限控制]模拟(Impersonation)与委托(Delegation)[上篇]
    深入剖析授权在WCF中的实现[共14篇]
    模拟在WCF中的应用
    WCF服务端运行时架构体系详解[下篇]
    WCF运行时框架的构建与扩展[共10篇]
    如何在EHAB(EntLib)中定义”细粒度”异常策略?
    WCF服务端运行时架构体系详解[续篇]
    《WCF服务编程》关于“队列服务”一个值得商榷的地方
    vs2005入门 之 结构化数据类型[一](数组)[视频]
    Atlas入门UpdateProgress(利用GridView翻页)[视频]
  • 原文地址:https://www.cnblogs.com/yuandongtao1989/p/6692846.html
Copyright © 2011-2022 走看看