【发布时间】:2014-03-08 16:46:18
【问题描述】:
以下代码的目的是创建一个仅使用基本数组操作的 strcat 函数。目标字符数组由用户输入,源字符数组附加到它的末尾。除了它为某些输入字符数组吐出的随机字符外,我的代码大部分都可以正常工作。例如,如果我的目标输入是奶酪,源输入是汉堡,那么输出应该是芝士汉堡。但是,如果我的目标输入是龙而我的源输入是苍蝇,那么蜻蜓应该是输出。但是,输出为dragonfly@。我不知道出了什么问题,需要帮助。
#include <iostream>
#include <string>
using namespace std;
void mystrcat ( char destination[], const char source[]);
int main(){
char source[80];
char destination[80];
cout << "Enter a word: ";
cin >> source;
cout << "\n";
cout << "Enter a second word: ";
cin >> destination;
mystrcat(destination, source);
}
void mystrcat ( char destination[], const char source[]){
int x=0;
for(int i=0; destination[i] != '\0'; i++)
{
if ( destination[i] != '\0')
{
x = x + 1;
}
}
for(int i=0; source[i] != '\0'; i++)
{
destination[i + x] = source[i];
}
cout << destination << endl;
}
【问题讨论】:
-
你需要null终止结果。
-
丢失索引,只使用指针。在此过程中,正确构造的附加循环将包括终止符。 See it live.
标签: c++ arrays string function strcat