用于将两个字符串进行拼接。它的原型定义在 <cstring>
或 <string.h>
头文件中:
char* strcat(char* destination, const char* source);
strcat
函数会将 source
字符串的内容追加到 destination
字符串的末尾,并返回指向 destination
字符串的指针。
以下是一个使用 strcat
的示例:
#include <cstring> #include <iostream> int main() { char destination[20] = "Hello, "; const char* source = "world!"; strcat(destination, source); std::cout << "Concatenated string: " << destination << std::endl; return 0; }
输出结果将是:
Concatenated string: Hello, world!
需要注意的是,destination
字符数组必须有足够的空间来容纳要追加的字符串,否则可能导致缓冲区溢出的问题。此外,strcat
函数要求 destination
和 source
字符串都以 null 终止符结束。
在 C++ 中,更推荐使用 std::string
类型的 +
运算符或者 append
成员函数来进行字符串的拼接操作。这些方式更安全、更方便,并且没有缓冲区溢出的风险。