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++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。