名稱空間
變體
操作

std::strncpy

來自 cppreference.com
< cpp‎ | string‎ | byte
在標頭檔案 <cstring> 中定義
char* strncpy( char* dest, const char* src, std::size_t count );

src 所指向的位元組字串(包括終止空字元)中最多 count 個字元複製到 dest 所指向的字元陣列中。

如果在複製整個字串 src 之前達到 count,則生成的字元陣列不是以 null 結尾的。

如果從 src 複製終止空字元後,count 未達到,則會將額外的空字元寫入 dest,直到寫入的字元總數達到 count

如果字串重疊,則行為未定義。

目錄

[編輯] 引數

dest - 指向要複製到的字元陣列的指標
src - 指向要複製的位元組字串的指標
count - 要複製的最大字元數

[編輯] 返回值

dest

[編輯] 示例

#include <cstring>
#include <iostream>
 
int main()
{
    const char* src = "hi";
    char dest[6] = {'a', 'b', 'c', 'd', 'e', 'f'};
    std::strncpy(dest, src, 5);
 
    std::cout << "The contents of dest are: ";
    for (char c : dest)
    {
        if (c)
            std::cout << c << ' ';
        else
            std::cout << "\\0" << ' ';
    }
    std::cout << '\n';
}

輸出

The contents of dest are: h i \0 \0 \0 f

[編輯] 參閱

將一個字串複製到另一個字串
(函式) [編輯]
將一個緩衝區複製到另一個緩衝區
(函式) [編輯]
C 文件 關於 strncpy