C语言sprintf()函数:将格式化的数据写入字符串

本文详细介绍了sprintf函数的功能和用法,包括如何将格式化的数据写入字符串、常见的使用场景及注意事项,例如防止缓冲区溢出等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

头文件:#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()讲解

<cstdio>

sprintf

int sprintf ( char * str, const char * format, ... );
Write formatted data to string
Composes a string with the same text that would be printed if  format was used on  printf, but instead of being printed, the content is stored as a  C string in the buffer pointed by  str.

The size of the buffer should be large enough to contain the entire resulting string (see  snprintf for a safer version).

A terminating null character is automatically appended after the content.

After the  format parameter, the function expects at least as many additional arguments as needed for  format.

Parameters

str
Pointer to a buffer where the resulting C-string is stored.
The buffer should be large enough to contain the resulting string.
format
C string that contains a format string that follows the same specifications as  format in  printf (see  printf for details).
...  (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.

Return Value

On success, the total number of characters written is returned. (sprintf函数会返回缓冲区中字符数量) This count does not include the additional null-character automatically appended at the end of the string.
On failure, a negative number is returned.

Example

1
2
3
4
5
6
7
8
9
10
11
/* sprintf example */
#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);
  return 0;
}


Output:
[5 plus 3 is 8] is a string 13 chars long


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值