c++将两个字符串连接起来,不用strcat
时间: 2023-12-15 12:30:45 浏览: 63
以下是两种C++将两个字符串连接起来的例子,不使用strcat函数:
1.使用循环遍历字符串并将其连接起来:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[80], str2[40];
int i = 0, j = 0;
cout << "please enter the first string:";
cin.getline(str1, 80);
cout << "please enter the second strings:";
cin.getline(str2, 40);
while (str1[i] != '\0') {
i++;
}
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
str1[i] = '\0';
cout << "After some characters string is:" << str1 << endl;
return 0;
}
```
2.使用指针遍历字符串并将其连接起来:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[80], str2[40], *p1, *p2;
cout << "please enter the first string:";
cin.getline(str1, 80);
cout << "please enter the second strings:";
cin.getline(str2, 40);
p1 = str1;
p2 = str2;
while (*p1) {
p1++;
}
while (*p2) {
*p1 = *p2;
p1++;
p2++;
}
*p1 = '\0';
cout << "After some characters string is:" << str1 << endl;
return 0;
}
```