Search code examples
c++charconcatenationcommand-line-argumentsstrlen

Best way to concatenate command line args


I have optind pointing to my first non-switch argument. There can be any number of arguments total. I need to concatenate the remaining args into a char*. I have a loop that goes from arg[optind] to arg[argc-1] and gets the (length + 1) of each (one for spaces between args and one for '\0' at the end: totalLen += strlen(arg[i]) + 1. Once I have the length though what is the best route to use to concatenate the args through another loop?


Solution

  • You can use a std::string and it's operator +=() and loop through argv[] and add the parameters to the string.

    std::string non_switch;
    for (int i = optind; i < argc; i++)
        non_switch += argv[i];