Joe S Joe S - 2 months ago 12
C++ Question

Concating a char array to the end of another char array (without built in functions)

I have been stuck on this for a few hours now, I am required to concatenate one string to the end of another and then store the results in a third string (without the use of pre-built functions. I am having a hard time of trying to store my results into another string, I was able to get a glimpse of what I wanted however it results in an infinite loop and does not seem effective. Can anyone shine some light on this?

#include <iostream>

using namespace std;

void Concat(char arr1[], char arr2[], char arr3[]);

int main(){

char arr1[] = {"Hello how are you? \0 "};
char arr2[] = { "The weather was cloudy today, so it rained. \0" };
char arr3[] = { "Coffee is a great way to start the day. \0" };

Concat(arr1, arr2, arr3);
}

void Concat(char arr1[], char arr2[], char arr3[]){

while (arr1 != '\0' && arr2 != '\0') {

// (This outputs what a want, haveing string 2 concat to the end of the firs string)
// However there is no way to save it to another array or stop the infinte loop.
//cout << arr1 << arr2 << endl;

arr1 + arr2 = arr3; // syntax error

}


}

Answer

You may want to try sth like this:

#include <iostream>

void concat(const char *arr1, const char *arr2, char *arr3);

int main(){
    const char *arr1("abc");
    const char *arr2("def");
    char arr3[10];

    concat(arr1, arr2, arr3);
    std::cout << "arr3 is " << arr3 << std::endl;
}

void concat(const char *arr1, const char *arr2, char *arr3){

    if (arr1) {
        while(*arr1 != '\0') {
            *arr3 = *arr1;
            ++arr1; ++arr3;
        }
    }

    if (arr2) {
        while(*arr2 != '\0') {
            *arr3 = *arr2;
            ++arr2; ++arr3;
        }
    }

    *arr3 = '\0';
}