Search code examples
c++c-stringsstrcpystrcat

How can I copy multiple char* strings into one using strcpy_s()?


Using the strcpy_s() function I want to collate the first three strings into the final one to print my full name. This is what I have and it doesn't work as I'm using char* strings and not std::strings.

#include <iostream>
using namespace std;

int main()
{
    char str_first[] = "Nerf_";
    char str_middle[] = " Herder";
    char str_last[] = "42";

    char str_fullName[35];

    strcpy_s(str_fullName, (str_first + str_middle + str_last).c_str());
    cout << str_fullName;
}

Any suggestions?


Solution

  • You need to use both strcat and strcpy

    See code comments for more info.

    // disable SDL warnings in Visual studio
    #define _CRT_SECURE_NO_WARNINGS
    
    #include <cstring>
    #include <iostream>
    using namespace std;
    
    int main()
    {
        // TODO: insert checking code,
        // to make sure destination can hold all characters + one termination.
    
        char str_first[] = "Nerf_";
        char str_middle[] = " Herder";
        char str_last[] = "42";
    
        char str_fullName[35];
    
        // copy first string because we need null terminated destination
        strcpy(str_fullName, str_first);
    
        // append the rest, string is auto null terminated.
        strcat(str_fullName, str_middle);
        strcat(str_fullName, str_last);
    
        cout << str_fullName;
    }