strcat函数使用char数组

时间:2014-03-08 16:46:19

标签: c++ arrays string function strcat

以下代码的目的是仅使用基本数组操作创建一个strcat函数。目标字符数组由用户输入,源字符数组附加到其末尾。我的代码工作得很好,除了它为某些输入字符数组吐出的随机字符。例如,如果我的目的地输入为奶酪而我的源输入为汉堡,则输出为芝士汉堡,应该如此。但是如果我的目标输入是龙并且我的源输入是fly,则应该输出dragonfly。但是,输出是以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;
}

3 个答案:

答案 0 :(得分:0)

您不会终止目标字符串。您需要在最后添加'\0'字符。

答案 1 :(得分:0)

基本上,您只需要在'\0'数组的末尾添加一个空字符(destination)。

这是正确的(并略微简化)实现:

void mystrcat(char destination[], const char source[])
{
    int x = 0;
    while (destination[x] != '\0')
    {
        x++;
    }
    for (int i=0; source[i] != '\0'; i++)
    { 
        destination[x++] = source[i];
    }
    destination[x] = '\0';
}

但是你应该知道你对destination数组的大小没有安全断言......

答案 2 :(得分:0)

短代码:

void _mystrcat_(
__in char * out,
__in char * in)
{
    while (*out) out++;
    do { *out++ = *in++; } while (*in);
   *out = 0x0;
}
相关问题