C++ strncpy() 函數 C++ 中的strncpy() 函數將指定字節的字符從源複製到目標。
strncpy()原型
char* strncpy( char* dest, const char* src, size_t count );
strncpy()
函數接受三個參數:dest、src 和 count。它將最大計數字符從 src
指向的字符串複製到 dest
指向的內存位置。
如果 count 小於 src
的長度,則第一個 count 字符被複製到 dest
並且它不是以 null 結尾的。如果 count
大於 src
的長度,則將 src 中的所有字符複製到 dest
並添加額外的終止空字符,直到總共寫入了 count 個字符。
如果字符串重疊,則行為未定義。
它在<cstring> 頭文件中定義。
參數:
dest
:指向內容複製到的字符數組的指針。src
:指向從中複製內容的字符數組的指針。count
:要複製的最大字符數。
返回:
strncpy() 函數返回 dest,即指向目標內存塊的指針。
示例:strncpy() 函數的工作原理
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char src[] = "It's Monday and it's raining";
char dest[40];
/* count less than length of src */
strncpy(dest,src,10);
cout << dest << endl;
/* count more than length of src */
strncpy(dest,src,strlen(src)+10);
cout << dest << endl;
return 0;
}
運行程序時,輸出將是:
It's Monday It's Monday and it's raining
相關用法
- C++ strncat()用法及代碼示例
- C++ strncmp()用法及代碼示例
- C++ string::length()用法及代碼示例
- C++ strchr()用法及代碼示例
- C++ string::npos用法及代碼示例
- C++ strcat()用法及代碼示例
- C++ strstr()用法及代碼示例
- C++ strcat() vs strncat()用法及代碼示例
- C++ strtok()用法及代碼示例
- C++ strtod()用法及代碼示例
- C++ strtoimax()用法及代碼示例
- C++ strcmp()用法及代碼示例
- C++ strcspn()用法及代碼示例
- C++ strpbrk()用法及代碼示例
- C++ strxfrm()用法及代碼示例
- C++ strspn()用法及代碼示例
- C++ strtoull()用法及代碼示例
- C++ string at()用法及代碼示例
- C++ strol()用法及代碼示例
- C++ strtoll()用法及代碼示例
注:本文由純淨天空篩選整理自 C++ strncpy()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。