使用char数组的strcat函数

strcat function using char arrays

本文关键字:strcat 函数 数组 char 使用      更新时间:2023-10-16

以下代码的目的是仅使用基本数组操作创建一个strcat函数。用户输入目标char数组,并将源字符阵列附加到其末尾。除了它在某些输入char阵列中吐出的随机字符外,我的代码最有效。例如,如果我将目的地输入为奶酪,而我的来源输入为汉堡,则输出是芝士汉堡。但是,如果我的目的地输入是龙,而我的来源输入是飞,则蜻蜓应该是输出。但是,输出作为蜻蜓@。我不知道怎么了,需要帮助。

#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] != ''; i++)
    {
        if ( destination[i] != '')
        {
            x = x + 1;
        }
    }
    for(int i=0; source[i] != ''; i++)
    { 
        destination[i + x] = source[i];
    }
    cout << destination << endl;
}

基本上,您只需要在destination数组的末尾添加一个null-character( '')。

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

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

,但您应该知道您对destination数组的大小没有安全性征象...

您不会终止目标字符串。您需要在末尾添加''字符。

简短代码:

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