Joe4444
Joe4444

Reputation: 21

How to concatenate command line arguments with separator

I read from argv the arguments and i want to put them into only one string. For example if the arguments are : man ls -la, then i want to get command string "man ls -la" in one string

Here is what i currently have:

#include <string>
int main(int argc, char**argv) { 

    string command;
    for (int i = 1; i<argv; i++) {
        command += argv[i]; 
    }

    my_function(command); 
}

command should contain all the arguments separate by a space:

Is this correct ?

I also have a compiler error:

error C2446: '<': no conversion from 'char **' to 'int'

Where is this error coming from?

Upvotes: 1

Views: 2333

Answers (2)

Shakiba Moshiri
Shakiba Moshiri

Reputation: 23864

A simple way:

std::string argument;
std::for_each( argv + 1, argv + argc , [&]( const char* c_str ){ argument += std::string ( c_str ) + " "; } );
std::cout << argument;  

or write you join function:

struct Join{
    template< typename Container >
    std::string operator()( Container first, Container last,const std::string& delimiter = " " ){

        std::ostringstream oss;
        while( first != last ){
            ( ( first + 1 ) != last ) ? ( oss << *first << delimiter ) : ( oss << *first );
            ++first;
        }

        return oss.str();
    }
}join;

usage:

std::string result = join( argv + 1, argv + argc );
std::cout << result << '\n';

Upvotes: 2

4386427
4386427

Reputation: 44329

The compiler error you get is because you use argv in your for instead of argc, here is the correct version:

for(int i = 1; i < argc;i++) {...}

You also need to add a space after each argument (except the last time)

for (int i = 1; i<argc; i++) {
    command += argv[i];

    if (i != argc-1) //this check prevents adding a space after last argument.
        command += " ";
}

or add the space before each argument (except the first time)

for (int i = 1; i<argc; i++) {
    if (i != 1)
        command += " ";

    command += argv[i];
}

Please note that you start your iteration from the first element (for(int i = 1 ...). This skips the first argument that is always the executable name.

Upvotes: 1

Related Questions