sprintf_s函数用法

sprintf_s是一个函数,其函数功能是将数据格式化输出到字符串。sprintf_s对于格式化string中的格式化的字符的有效性进行了检查,sprintf_s也携带着接收格式化字符串的缓冲区的大小。
sprintf_s将格式化字符串存到缓冲区,如果格式化字符串过大,则sprintf_s会返回一个空string和设置无效参数句柄为激活。
函数原型:
int sprintf_s(
char *buffer,
size_t sizeOfBuffer,
const char *format [,
argument] ...
);
sprintf_s()是sprintf()的安全版本,通过指定缓冲区长度来避免sprintf()存在的溢出风险
相关函数:
int sprintf( char *buffer, const char *format [, argument] … );
int vsprintf( char *buffer, const char *format, va_list argptr );
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++ only
template <size_t size>
int swprintf_s(
wchar_t (&buffer)[size],
const wchar_t *format [,
argument]...
); // C++ only

// crt_sprintf_s.c
// This program uses sprintf_s to format various
// data and place them in the string named buffer.
//
#include <stdio.h>
int main( void )
{
char buffer[200], s[] = "computer", c = 'l';
int i = 35, j;
float fp = 1.7320534f;
// Format and print various data:
j = sprintf_s( buffer, 200, " String: %s\n", s );
j += sprintf_s( buffer + j, 200 - j, " Character: %c\n", c );
j += sprintf_s( buffer + j, 200 - j, " Integer: %d\n", i );
j += sprintf_s( buffer + j, 200 - j, " Real: %f\n", fp );
printf_s( "Output:\n%s\ncharacter count = %d\n", buffer, j );
}
Output:
String: computer
Character: l
Integer: 35
Real: 1.732053
character count = 79

附:https://baike.baidu.com/item/sprintf_s/8673108?fr=aladdin

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读