用sizeof实现上述代码
时间: 2024-01-02 13:19:26 浏览: 26
使用C++中的sizeof操作符计算字符串长度的代码如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char str1[100], str2[100];
char *new_str;
cout << "请输入第一个字符串:";
cin >> str1; // 从键盘输入第一个字符串
cout << "请输入第二个字符串:";
cin >> str2; // 从键盘输入第二个字符串
int len1 = sizeof(str1) - 1; // 计算第一个字符串的长度
int len2 = sizeof(str2) - 1; // 计算第二个字符串的长度
int len_new = len1 + len2 + 1; // 计算新字符串的长度
new_str = new char[len_new]; // 动态分配内存
strcpy(new_str, str1); // 复制第一个字符串到新字符串中
strcat(new_str, str2); // 追加第二个字符串到新字符串中
new_str[len_new - 1] = '\0'; // 在新字符串末尾添加结束符
cout << "连接后的字符串为:" << new_str << endl; // 输出新字符串
delete[] new_str; // 释放动态分配的内存
return 0;
}
```
其中,sizeof(str1)返回的是包括字符串结束符在内的数组str1的总长度,因此需要减去1才能得到字符串的长度。同理,sizeof(str2)也需要减去1。