5

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.

3
  • add .c_str() to the end of strings[0]; you'll still have to build another vector of pointers for the second parameter though. Commented Oct 20, 2013 at 20:32
  • Assuming strings is a std::vector<std::string>, use strings[0].c_str(). the second paramater needs an array of pointers, so that's more complex. Commented Oct 20, 2013 at 20:33
  • Instead of the getline, you can simply say while (f >> x) { strings.push_back(x); }. Commented Oct 20, 2013 at 21:02

3 Answers 3

7

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());
Sign up to request clarification or add additional context in comments.

16 Comments

Not enough transform :) I've just added a C++03 proof transform answer. Painful stuff
@sehe: I can never quite be bothered with transform. I always feel it's a lot of work with no gain.
@KerrekSB Yeah, Boost Range has transformed, which is a lot more useful indeed. However, before C++11 I think it was frequently a "better for_each"
I've changed it from strings[i].front() to strings[i][0] so it is always correct, independent of whether the string is empty.
@KerrekSB : I'm fine with std::vector, but I still have problems remembering how char *s get initialized!
|
1

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.

Comments

0

If the char array will not be changed you can use

strings[0].c_str()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.