在本教程中,我們將借助示例了解 C++ strcpy() 函數。
C++ 中的strcpy() 函數將字符串從源複製到目標。它在cstring 頭文件中定義。
示例
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char src[] = "Hello Programmers.";
// large enough to store content of src
char dest[20];
// copy the contents of src to dest
strcpy(dest,src);
cout << dest;
return 0;
}
// Output: Hello Programmers.
strcpy() 語法
用法:
strcpy( char* dest, const char* src );
參數:
strcpy() 函數采用以下參數:
- dest- 指向內容被複製到的C-string
- src- 指向複製內容的C-string 的指針
返回:
strcpy() 函數返回:
dest(指向目標的指針C-string)
strcpy() 原型
cstring 頭文件中定義的strcpy() 原型為:
char* strcpy(char* dest, const char* src);
strcpy() 函數將 src 指向的 C-string 複製到 dest 指向的內存位置。空終止字符'\0' 也被複製。
請注意:
src屬於const char*類型。const關鍵字確保src指向的 C-string 不能被strcpy()修改。dest屬於char*類型。const的缺失確保了dest指向的 C-string 可以被strcpy()修改。
strcpy() 未定義行為
的行為strcpy()是不明確的如果:
- 為
dest指針分配的內存不夠大。 - 琴弦重疊。
示例:C++ strcpy()
#include <cstring>
#include <iostream>
using namespace std;
int main() {
char src[20] = "I am the source.";
// large enough to store content of src
char dest[30] = "I am the destination.";
cout << "dest[] before copy: " << dest << endl;
// copy contents of src to dest
strcpy(dest,src);
cout << "dest[] after copy: " << dest;
return 0;
}
輸出
dest[] before copy: I am the destination. dest[] after copy: I am the source.
相關用法
- C++ strchr()用法及代碼示例
- C++ strcat()用法及代碼示例
- C++ strcat() vs strncat()用法及代碼示例
- C++ strcmp()用法及代碼示例
- C++ strcspn()用法及代碼示例
- C++ strcoll()用法及代碼示例
- C++ string::length()用法及代碼示例
- C++ string::npos用法及代碼示例
- C++ strncat()用法及代碼示例
- C++ strstr()用法及代碼示例
- C++ strtok()用法及代碼示例
- C++ strtod()用法及代碼示例
- C++ strtoimax()用法及代碼示例
- C++ strpbrk()用法及代碼示例
- C++ strxfrm()用法及代碼示例
- C++ strspn()用法及代碼示例
- C++ strncmp()用法及代碼示例
- C++ strtoull()用法及代碼示例
- C++ string at()用法及代碼示例
- C++ strol()用法及代碼示例
注:本文由純淨天空篩選整理自 C++ strcpy()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
