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

头文件:#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 所指的字符串数组,直到出现字符串结束(‘\0‘)为止。关于参数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]=‘\n‘;
  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
时间: 2024-08-08 05:36:19

sprintf用法的相关文章

sprintf 用法

字符串格式化命令,主要功能是把格式化的数据写入某个字符串中 试试下面的代码就知道了 1 #include<cstdio> 2 #include<cstdlib> 3 using namespace std; 4 int main() 5 { 6 double num=3.123456677; 7 char str[100]; 8 sprintf(str,"%.3lf",num); 9 sprintf(str,"%.4lf",num); 10

sscanf,sprintf用法

#include<string.h> #include<stdio.h> int main() { char buf[512],sztime1[16],sztime2[16]; sscanf("123456 ", "%s", buf);//此处buf是数组名,它的意思是将123456以%s的形式存入buf中! printf("%s\n", buf); sscanf("123456 ", "%4

sprintf()详细介绍

sprintf 编辑词条 编辑词条 --> 字串格式化命令,主要功能是把格式化的数据写入某个字符串中.sprintf 是个变参函数,使用时经常出问题,而且只要出问题通常就是能导致程序崩溃的内存访问错误,但好在由sprintf 误用导致的问题虽然严重,却很容易找出,无非就是那么几种情况,通常用眼睛再把出错的代码多看几眼就看出来了.[1]由于sprintf 跟printf 在用法上几乎一样,只是打印的目的地不同而已,前者打印到字符串中,后者则直接在命令行上输出.这也导致sprintf 比printf

WordPress翻译中 __()、_e()、_x、_ex 和 _n 的用法及区别

编译函数 WordPress使用了下面几个函数来方便语言本地化. __() _e() _x() _ex() _n() 以上所列的函数是用来包含所需翻译的字符串的,根据字符串的不同参数和输出类型,需要使用不同的函数.相信有不少朋友还是不太明白这几个函数的区别和用法,下面倡萌就来详细说说. __() 和 _e() __() 和 _e() 都是用来返回对应当前语言的字符串内容.请看下面的例子: 使用 __() <?php if( is_single() ) { //如果这是一篇“文章” echo __

Smrty模版总结(转)

转自:http://www.cppblog.com/amazon/archive/2011/11/21/160638.html 前提:1. 部署smarty模板目录:2. 编写Smarty类的子类,定制好template_dir.compile_dir.config_dir.cache_dir.left_delimiter.right_delimiter.compile_check.caching等配置信息.3. 在BaseAction类中定义该类对象,然后便可使用.4. 暂定delimiter

PostgreSQL 9.3 格式化拼接字符串

2013-05-06 08:39:20|  分类: PgSQL Develop|举报|字号 订阅 PostgreSQL 9.3 引入的一个格式化输出函数, 有点类似C的sprintf用法. 语法如下 : format(formatstr text [, formatarg "any" [, ...] ]) 其中formatstr是需要格式化的字符串, 包含普通字符以及格式字符. 后面的动态参数用来替换formatstr中的格式字符. 格式字符的语法如下 : %[position][fl

smarty基础总结

前提: 1. 部署smarty模板目录: 2. 编写Smarty类的子类,定制好template_dir.compile_dir.config_dir.cache_dir.left_delimiter.right_delimiter.compile_check.caching等配置信息. 3. 在BaseAction类中定义该类对象,然后便可使用. 4. 暂定delimiter使用{和} 一. 变量 1. php变量 A. 普通变量:{$var} B. 关联数组:{$array.var1.var

PHP基础温习之echo print printf sprintf print_r var_dump的用法与区别

原文:PHP基础温习之echo print printf sprintf print_r var_dump的用法与区别 一.echoecho() 实际上不是一个函数,是php语句,因此您无需对其使用括号.不过,如果您希望向 echo() 传递一个以上的参数,那么使用括号会发生解析错误.而且echo是返回void的,并不返回值,所以不能使用它来赋值.例子: 复制代码代码如下: <?php $a = echo("55nav"); // 错误!不能用来赋值 echo "55n

echo print printf sprintf print_r var_dump的用法与区别

一.echoecho() 实际上不是一个函数,是php语句,因此您无需对其使用括号.不过,如果您希望向 echo() 传递一个以上的参数,那么使用括号会发生解析错误.而且echo是返回void的,并不返回值,所以不能使用它来赋值.例子: 复制代码代码如下: <?php $a = echo("55nav"); // 错误!不能用来赋值 echo "55nav"; // 55nav echo ("55nav"); // 55nav echo (