简体   繁体   中英

strcat function using char arrays

The purpose of the following code was to create an strcat function using only basic array manipulation. A destination char array is input by a user and a source char array is appended to the end of it. My code works mostly fine except for the random chars it spits out for certain input char arrays. For example if I have my destination input as cheese and my source input as burger, the output is cheeseburger, as it should be. However if my destination input is dragon and my source input is fly, dragonfly should be the output. However, the output is given as dragonfly@. I have no idea what's wrong, and need help.

#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;
}

You don't terminate the destination string. You need to add the '\\0' character at the end.

Basically, you just need to add a null-character ( '\\0' ) at the end of the destination array.

Here is the correct (and slightly simplified) implementation:

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';
}

But you should be aware that you have no safety-assertion on the size of the destination array...

short code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM