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.
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With