简体   繁体   中英

Convert string vector to char array in 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.

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, ie char * which you need for execvpe . Check this link for more details.

如果char数组不会被更改,您可以使用

strings[0].c_str()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM