Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string vector to char array in c++

Tags:

c++

I'm trying to convert a string vector to a char array in c++.

More specifically what I'm trying to do is to split a shell command like "ls –latr" by using this:

istringstream f(x);
while (getline(f, x, ' '))
{
    strings.push_back(x);
}

I believe that will give me strings[0] == "ls" and strings[1]==" -latr".

I'm trying then to do the following:

execvp(strings[0], strings);

however, I get this error:

error: cannot convert ‘std::basic_string, std::allocator >’ to ‘const char*’ for argument ‘1’ to ‘int execvp(const char*, char* const*)’

Therefore, I'm trying to figure out how I can convert the strings to a char array.

like image 808
Eric Avatar asked Mar 21 '23 23:03

Eric


2 Answers

Reading the manual reveals that "execvp provides an array of pointers to null-terminated strings". So you need to create such an array. Here's one way:

std::vector<char *> argv(strings.size() + 1);    // one extra for the null

for (std::size_t i = 0; i != strings.size(); ++i)
{
    argv[i] = &strings[i][0];
}

execvp(argv[0], argv.data());
like image 127
Kerrek SB Avatar answered Apr 01 '23 14:04

Kerrek SB


You may try with c_str() method of std::string. It returns C-like string from the std::string class, i.e. char * which you need for execvpe. Check this link for more details.

like image 27
Igor Popov Avatar answered Apr 01 '23 14:04

Igor Popov