strcpy:
語法:
#include <string.h>
char *strcpy( char *to, const char *from );
- 1
- 2
- 3
功能:復制字符串from 中的字符到字符串to,包括空值結束符。返回值為指針to。由於沒有字符串長度的限制,所以復制過程中遇到過長的字符串可能會發生未知的錯誤。
strcpy_s:
語法:
#include<string.h>
errno_t __cdecl strcpy_s(char*_Destination,rsize_t _SizeInBytes,char const* _Source);
- 1
- 2
功能:復制字符串_Source中的字符到字符串_Destination,其中限制了大小為_SizeInBytes,這是為了防止字符串過長超出緩存區內存引發問題而要求的。
在VS2015中使用strcpy的時候會給出error C4996: This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.這樣我們可以按照上面的語法換成使用strcpy_s,也可以選擇不產生警告,在程序開頭加上
#define _CRT_SECURE_NO_WARNINGS
- 1
即可,但要注意字符串不可太長。
實例1(strcpy_s):
#include<iostream>
#include<string>
using namespace std;
const int N = 2;
void main()
{
char *strings[N];
char str[80];
cout << "At each prompt, enter a string:\n";
for (int i = 0; i < N; i++) {
cout << "Ener a string #" << i << ":";
cin.getline(str, sizeof(str));
strings[i] = new char[strlen(str) + 1];
strcpy_s(strings[i], strlen(str) + 1, str);
}
cout << endl;
for (int i(0); i < N; i++)
cout << "String #" << i << ":" << strings``
] << endl;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
實例2(strcpy):
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
const int N = 2;
void main()
{
char *strings[N];
char str[80];
cout << "At each prompt, enter a string:\n";
for (int i = 0; i < N; i++) {
cout << "Ener a string #" << i << ":";
cin.getline(str, sizeof(str));
strings[i] = new char[strlen(str) + 1];
strcpy(strings[i], str);
}
cout << endl;
for (int i(0); i < N; i++)
cout << "String #" << i << ":" << strings[i] << endl;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20