C stdio sprintf() 函数
定义和用法
sprintf()
函数将格式化字符串以及 '\0
' 空终止字符写入字符数组。
sprintf()
函数定义在 <stdio.h>
头文件中。
格式字符串可以包含格式说明符,这些说明符描述了如何以及在何处表示传递给函数的额外参数。
有关格式说明符的详细信息,请参阅 printf()
参考页面。
注意:此函数不考虑数组的大小。如果写入的字符过多,可能会开始覆盖属于其他变量或其他程序的内存。一个安全的替代函数是 snprintf()
。
实例
将一个格式化字符串写入一个字符数组:
char destination[50]; sprintf(destination, "Hello %s!", "World"); printf("%s", destination);
语法
sprintf(char * destination, const char * format, arg1, arg2...);
参数
参数 | 描述 |
---|---|
destination | 必需。字符数组,格式化字符串将被写入其中。 |
format | 必需。字符串,表示要写入数组的数据的格式。 |
arg1, arg2... | 可选。任意数量的额外参数,值可根据 format 参数中的说明符进行格式化并写入目标数组。 |
技术细节
返回: |
如果发生错误,则返回负数。 |
---|