Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

C++ Strcat Function In C++

rahulsharma

New Coder
I'm new to C and C++ programming, can anyone give me a hint on what I'm doing wrong here. I'm trying to write to concat function that takes to pointers to chars and concatenates the second to the first. The code does do that, but the problem is that it adds a bunch of junk at the end.

For instance, when passing the arguments - "green" and "blue", the output will be "greenblue" plus a bunch of random characters. I also wrote the strlen function that strcat uses, which I will provide below it for reference. I'm using the online compiler at https://www.interviewbit.com/online-cpp-compiler/ or http://cpp.sh/ The exact instructions and specification is this:


C++:
int main(int argc, char** argv)
{
const int MAX = 100;

char s1[MAX];
char s2[MAX];

cout << "Enter your first string up to 99 characters. ";
cin.getline(s1, sizeof(s1));
int size_s1 = strlen(s1);
cout << "Length of first string is " << size_s1 << "\n";

cout << "Enter your second string up to 99 characters. ";
cin.getline(s2, sizeof(s2));
int size_s2 = strlen(s2);
cout << "Length of second string is " << size_s2 << "\n";
cout << " Now the first string will be concatenated with the second
string ";
char* a = strcat(s1,s2);

for(int i = 0; i<MAX; i++)
cout <<a[i];

// system("pause");
return 0;
}

//strcat function to contatenate two strings
char* strcat(char *__s1, const char *__s2)
{
int indexOfs1 = strlen(__s1);
int s2L = strlen(__s2);
cout <<s2L << "\n";
int indexOfs2 = 0;
do{
__s1[indexOfs1] = __s2[indexOfs2];
indexOfs1++;
indexOfs2++;
}while(indexOfs2 < s2L);


return __s1;
}

//Returns length of char array
size_t strlen(const char *__s)
{
int count = 0;
int i;
for (i = 0; __s[i] != '\0'; i++)
count++;
return (count) / sizeof(__s[0]);

}
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom