Why is the output missing the first letter when I use strcat() in c++?

91 Views Asked by At

Here I want to merge two char arrays and put them into the first char array But when I cout the second one, it is missing the first letter. why?

#include <bits/stdc++.h>
using namespace std;
int main() {
    
    char s1[4] = "one";
    char s2[4] = "two" ;
    
    strcat(s1, s2);
    cout << s1 << endl; //onetwo
    
    cout  << s2; // wo

    return 0;
}
2

There are 2 best solutions below

0
Andreas Wenzel On

When calling the function strcat, it is required that you pass as the first argument a pointer to a memory buffer that is large enough to store the concatenated string.

In your case, the concatented string has a length of 6 characters ("onetwo"), so the memory buffer must have a size of at least 7 characters (including the terminating null character). However, in your case, the memory buffer has a size of only 4 characters, which is insufficient. Therefore, your program is invoking undefined behavior, which means that anything can happen. This includes the behavior that you describe in the question.

To fix the problem, you must make the array s1 at least 7 characters long:

#include <iostream>
#include <cstring>

using namespace std;

int main() {
    
    char s1[7] = "one";
    char s2[4] = "two" ;
    
    strcat(s1, s2);

    cout << s1 << endl;    
    cout << s2 << endl;

    return 0;
}

This program has the desired output:

onetwo
two
0
Benjamin Buch On

In C++ you should use std::string for working with strings:

#include <iostream>
#include <string>

int main() {
    std::string s1 = "one";
    std::string s2 = "two";

    s1 += s1; // append s2 to s1

    std::cout << s1 << '\n';
    std::cout << s2 << '\n';
}
oneone
two