javascript is future
javascript is future

Reputation: 895

Using argument char argv[] in system()

I need to execute a perl script from my c++ code. This is done with system().
Now I need to pass the second argument from my code:

int main(int argc, char * argv[])

into my system() like this:

char *toCall="perl test.pl "+argv[1];
system(toCall);

Now it brings the error: "invalid operands of types ‘const char [14]’ and ‘char**’ to binary ‘operator+’"

What am I doing wrong?

Upvotes: 2

Views: 4951

Answers (2)

hmjd
hmjd

Reputation: 122001

You can't create a concatentated string by assigning char*. You need to use std::string or std::ostringstream:

std::ostringstream s;

s << "perl test.pl";
for (int i = 1; i < argc; i++)
{
    // Space to separate arguments.
    // You need to quote the arguments if
    // they can contain spaces.
    s << " " << argv[i];
}

system(s.str().c_str());

Upvotes: 2

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145359

Use std::string, like

std::string const command = std::string( "perl test.pl " ) + argv[1];
system( command.c_str() );

You cannot add two raw pointers.

But std::string provides an overload of the + operator.

Upvotes: 6

Related Questions