企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# C++ 程序:连接两个字符串 > 原文: [https://www.programiz.com/cpp-programming/examples/concatenate-string](https://www.programiz.com/cpp-programming/examples/concatenate-string) #### 在此示例中,您将学习连接(连接)两个字符串(字符串对象和 C 样式字符串)。 要理解此示例,您应该了解以下 [C++ 编程](/cpp-programming "C++ tutorial")主题: * [C++ 数组](/cpp-programming/arrays) * [C++ 字符串](/cpp-programming/strings) * * * 您可以使用`+`运算符在 C++ 中连接两个字符串对象。 * * * ## 示例 1:连接字符串对象 ```cpp #include <iostream> using namespace std; int main() { string s1, s2, result; cout << "Enter string s1: "; getline (cin, s1); cout << "Enter string s2: "; getline (cin, s2); result = s1 + s2; cout << "Resultant String = "<< result; return 0; } ``` **输出** ```cpp Enter string s1: C++ Programming Enter string s2: is awesome. Resultant String = C++ Programming is awesome. ``` 您可以使用`strcat()`函数在 C++ 中连接两个 C 样式的字符串。 * * * ## 示例 2:连接 C 样式字符串 ```cpp #include <iostream> #include <cstring> using namespace std; int main() { char s1[50], s2[50], result[100]; cout << "Enter string s1: "; cin.getline(s1, 50); cout << "Enter string s2: "; cin.getline(s2, 50); strcat(s1, s2); cout << "s1 = " << s1 << endl; cout << "s2 = " << s2; return 0; } ``` **输出** ```cpp Enter string s1: I love Enter string s2: C++ programming s1 = I love C++ programming s2 = C++ programming ```