Strcat Function In C++
Ayushsharma last edited by
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/ The exact instructions and specification is this:
int main(int argc, char** argv)
const int MAX = 100;
cout << "Enter your first string up to 99 characters. ";
int size_s1 = strlen(s1);
cout << "Length of first string is " << size_s1 << "\n";
cout << "Enter your second string up to 99 characters. ";
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
char* a = strcat(s1,s2);
for(int i = 0; i<MAX; i++)
//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;
__s1[indexOfs1] = __s2[indexOfs2];
}while(indexOfs2 < s2L);
//Returns length of char array
size_t strlen(const char *__s)
int count = 0;
for (i = 0; __s[i] != '\0'; i++)
return (count) / sizeof(__s);
DocShoe last edited by DocShoe
You forgot to append \0 at the end of the concatenated string.
btw: strings are handled different in C++, I hope this is for educational purpose only.
DirkB last edited by DirkB
for(int i = 0; i<MAX; i++)
This prints all the 100 (MAX) characters. When you only use 10, the rest is garbage.
The '\0' character indicates the border between text und garbage.
And its a bad idea to name own functions like functions from the standard library.
wob last edited by wob
The obvious response: when using C++, simply use
Assuming your strcat is correct (haven't looked at it), there are at least two bugs:
a) you check the lengths of s1 and s2 individually (by using a limit in the getline call). But you don't verify that the length of s1 + length of s2 is also smaller than 100.
b) you are simply outputting all 100 characters regardless of the actual string length in your for loop (
for(int i = 0; i<MAX; i++) cout <<a[i];)
Edit: I see that my assumption of a correct strcat is also ... wrong... Don't use double underscores (quote from [lex.name]: "Each identifier that contains a double underscore __ or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use."). Remember to put '\0' at the end. In strlen: no need for two variables i and count. No need to divide by 1 (sizeof char is 1 by definition [expr.sizeof]).