strcat()
strcat()函數會將源字符串的副本附加到目標字符串的末尾。 strcat()函數采用兩個參數:
1)dest
2)src
它將源字符串的副本追加到目標字符串中。 dest末尾的終止字符被src的第一個字符替換。返回值:strcat()函數返回目標字符串的指針dest。
// CPP program to demonstrate
// strcat
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char dest[50] = "This is an";
char src[50] = " example";
strcat(dest, src);
cout << dest ;
return 0;
}
輸出量
This is an example
C++中的strncat()函數將給定數量的字符從一個字符串追加到另一字符串的末尾.strncat()函數將采用以下三個參數:
1)dest
2)Src
3)count
這會將src字符串中給定數量的字符追加到dest字符串的末尾。 dest字符串末尾的終止字符將替換為src string的第一個字符。返回值:strncat()函數返回目標字符串的指針dest。
// CPP program to demonstrate
// strncat
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char dest[25] = "This is an example";
char src[50] = " to show working of strncat() this is not added";
strncat(dest, src, 29);
cout << dest ;
return 0;
}
輸出量
This is an example to show working of strncat()
How strncat() is different from strcat() ?
許多程序員建議strncat()與strcat()相比是安全的,因為strcat()不會檢查複製數據的大小,並且會一直複製到空終止符,這可能會導致緩衝區溢出,而strncat()會檢查緩衝區是否溢出。複製數據的大小,並且隻會複製“ n”個字節。
// C,C++ program demonstrate difference bewteen
// strncat() and strcat()
#include <stdio.h>
#include <string.h>
int main()
{
// Take any two strings
char src[50] = "forgeeks";
char dest1[50] = "geeks";
char dest2[50] = "geeks";
printf("Before strcat() function execution, ");
printf("destination string:%s\n", dest1);
// Appends the entire string of src to dest1
strcat(dest1, src);
// Prints the string
printf("After strcat() function execution, ");
printf("destination string:%s\n", dest1);
printf("Before strncat() function execution, ");
printf("destination string:%s\n", dest2);
// Appends 3 characters from src to dest2
strncat(dest2, src, 3);
// Prints the string
printf("After strncat() function execution, ");
printf("destination string:%s\n", dest2);
return 0;
}
輸出:
Before strcat() function execution, destination string:geeks After strcat() function execution, destination string:geeksforgeeks Before strncat() function execution, destination string:geeks After strncat() function execution, destination string:geeksfor
相關用法
注:本文由純淨天空篩選整理自 strcat() vs strncat() in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。