Append to the end of a Char array in C++

前端 未结 4 1744
我在风中等你
我在风中等你 2021-02-08 14:58

Is there a command that can append one array of char onto another? Something that would theoretically work like this:

//array1 has already been set to \"The dog         


        
相关标签:
4条回答
  • 2021-02-08 15:17

    If your arrays are character arrays(which seems to be the case), You need a strcat().
    Your destination array should have enough space to accommodate the appended data though.

    In C++, You are much better off using std::string and then you can use std::string::append()

    0 讨论(0)
  • 2021-02-08 15:25

    You should have enough space for array1 array and use something like strcat to contact array1 to array2:

    char array1[BIG_ENOUGH];
    char array2[X];
    /* ......             */
    /* check array bounds */
    /* ......             */
    
    strcat(array1, array2);
    
    0 讨论(0)
  • 2021-02-08 15:32

    There's no built-in command for that because it's illegal. You can't modify the size of an array once declared.

    What you're looking for is either std::vector to simulate a dynamic array, or better yet a std::string.

    std::string first ("The dog jumps ");
    std::string second ("over the log");
    std::cout << first + second << std::endl;
    
    0 讨论(0)
  • 2021-02-08 15:38

    If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.

    #include <cstring>
    #include <iostream>
    
    int main()
    {
        char array1[] ="The dog jumps ";
        char array2[] = "over the log";
        char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
        std::strcpy(newArray,array1);
        std::strcat(newArray,array2);
        std::cout << newArray << std::endl;
        delete [] newArray;
        return 0;
    }
    

    This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.

    Edit, a safe version with the "enough buffer space" assumption:

    #include <cstring>
    #include <iostream>
    
    int main()
    {
        const unsigned BUFFER_SIZE = 50;
        char array1[BUFFER_SIZE];
        std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
        char array2[] = "over the log";
        std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
        std::cout << array1 << std::endl;
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题