C++安全函数之strcpy_s
1. 必须包含的头文件:<string.h>
2. 函数声明:
errno_t strcat_s(
char *strDestination,
size_t numberOfElements,
const char *strSource
);
3. 参数介绍
strDestination 目标字符串缓冲区的位置。 numberOfElements 多字节窄函数 char 单元以及宽函数 wchar_t 单元中的目标字符串缓冲区的大小。 strSource 以 null 结尾的源字符串缓冲区。 |
4. 使用例子
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main( void )
{
char string[80];
// using template versions of strcpy_s and strcat_s:
strcpy_s( string, "Hello world from " );
strcat_s( string, "strcpy_s " );
strcat_s( string, "and " );
// of course we can supply the size explicitly if we want to:
strcat_s( string, _countof(string), "strcat_s!" );
printf( "String = %s\n", string );
system("Pause");
}
5. 注意事项
在使用strcpy_s,使用两个参数的时候要特别注意的一点是,两个参数但如果:char *str=new char[7];会出错:提示不支持两个参数。new出来的字符串,提示不支持两个参数,所以必须用三个参数的。
#include<iostream>
#include <string.h>
using namespace std;
void Test(void)
{
char *str1 = NULL;
str1 = new char[20];
char str[7];
strcpy_s(str1, 20, "hello world");//三个参数
strcpy_s(str, "hello");//两个参数但如果:char *str=new char[7];会出错:提示不支持两个参数
cout << "strlen(str1):"<<strlen(str1)<<endl<<"strlen(str):"<<strlen(str)<<endl;
cout << str1 << endl;
cout << str << endl;
}
int main()
{
Test();
system("Pause");
return 0;
}
输出为:strlen(str1): 11 //另外要注意:strlen(str1)是计算字符串的长度,不包括字符串末尾的“\0”!!!
strlen(str): 5
hello world
hello