我正在尝试用C++编写自己的strcat
函数,但它有一些问题。
我的输入是两个字符c
和a
,我的函数将返回一个字符指针,指向c
与a
连接的字符。
比如说,
输入:'abc'
'xyz'
预期输出:'xyzabc'
我的函数的输出:'xyza@▲∩'
我的函数返回一些与我的输入不同的特殊字符。
我调试了我的函数,发现:
- 当
i=0
时,destination[3]
=source[0]
='a'
- 但当
i=1
,destination[8]
=source[1]
='b'
时, - 当
i=2
,destination[9]
=source[2]
='c'
时 destination[10]
='\0'
#include<iostream>
#include<string.h>
using namespace std;
char* mystrcat ( char * destination, const char *source){
for (int i=0; i<strlen(source); i++) {
destination[strlen(destination)+i] = source[i];
}
destination[strlen(destination)+strlen(source)]='\0';
return destination;
}
int main() {
char c[100];
cin.getline(c, 99);
char a[100];
cin.getline(a,99);
mystrcat(a,c);
cout<<a;
return 0;
}
字符串
2条答案
按热度按时间0lvr5msh1#
strlen
返回从指针到它遇到的第一个\0
的长度。在这里,在循环期间,您在destination
指针中覆盖了这个字符,因此随后对strlen
的调用将返回内存中恰好保存这个字符的某个随机点的长度。一个简单的解决方法是在开始修改字符串之前提取
strlen
结果:字符串
e4eetjau2#
下面给出的是代码的正确实现。
字符串
由于源代码的长度将在代码中得到更新,因此它会给出特殊的符号作为输出。