sprintf_s和strcat_s函数的感悟


这是两个处理字符比较安全的函数,不会报警,相对的与原来的函数相比有些不同

C++中sprintf_s的原型如下:

int sprintf_s(
   char *buffer,
   size_t sizeOfBuffer,
   const char *format [,
   argument] ... 
);
http://msdn.microsoft.com/en-us/ce3zzk1k%28zh-cn%29.aspx#中,可以看到一个例子


// 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

第一个是字符串指针的首地址,第二个参数是缓冲区大小,后面是格式化字符和对应的参数;

而对于strcat_s函数,首先要确保连接的两个字符串都有内容,不然会报错,而且需要指出strcat_s函数的字符串缓冲区最大值,其原型如下:

errno_t strcat_s(
   char *strDestination,
   size_t numberOfElements,
   const char *strSource 
);
strcat_s函数包含在<string.h>头文件中。

展开阅读全文

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