ฟังก์ชัน strncat() ใน C++ ใช้สำหรับการต่อสตริง (concatenation) ฟังก์ชันนี้จะนำจำนวนตัวอักษรที่ระบุจากสตริงต้นทาง (source string) ไปต่อท้ายสตริงปลายทาง (destination string) และส่งคืนพอยน์เตอร์ไปยังสตริงปลายทาง ไวยากรณ์ของ strncat() มีดังนี้:
char * strncat ( char * dest, const char * src, size_t num );
จากไวยากรณ์ข้างต้น สตริงต้นทาง src จะถูกต่อท้ายสตริงปลายทาง dest จนครบ num ตัวอักษรเท่านั้น
โปรแกรมที่สาธิตการใช้งาน strcat() มีดังนี้: (หมายเหตุ: ตัวอย่างโค้ดใช้ strncat แต่คำอธิบายเขียนว่า strcat)
ตัวอย่าง
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[20] = "Programming is ";
char str2[20] = "fun";
strncat(str1, str2, 3);
cout << "The concatenated string is "<<str1;
return 0;
}ผลลัพธ์
The concatenated string is Programming is fun
ในโปรแกรมนี้ นิยามสตริงสองสตริง str1 และ str2 strncat() นำเนื้อหาของ str2 ไปต่อท้าย str1 จำนวน 3 ตัวอักษร และแสดงสตริงที่ต่อแล้วด้วย cout โค้ดส่วนนี้มีดังนี้:
char str1[20] = "Programming is "; char str2[20] = "fun"; strncat(str1, str2, 3); cout << "The concatenated string is "<<str1;