Is there a way to convert the above?
If so what i开发者_Python百科s the best way?
I guess you can loop through the vector and assign to a const char*
, but I'm not sure if that is the best way.
std::string s(vec.begin(), vec.end());
// now use s.c_str()
I think this should be fairly safe.
Maybe you could use a std::string
instead of the std::vector<char>
?
I believe std::string
is similar to std::vector<char>
so you can use it the same way, and benefit of its additional functions.
If so, std::string
has a method .c_str()
that returns a null-terminated C-string (a const char*
).
You can do something like this:
std::string str(&myVec[0], myVec.size());
And then str.c_str()
will return you a const char *
to play with. But this is assuming that the data in the vector is null-terminated. If it is not, then there are no guarantees.
Try the simple
LPCSTR str = &vec[0];
A vector already contains the contiguous storage that C strings require. But be careful that vec
is already null-terminated, and that vec
cannot be destroyed while str
is still used. Generally vec
can be destroyed as soon as it is not used anymore, so storing pointers into vec
is dangerous and will lead to crashes. OTOH, passing the pointer as argument might be fine:
f(&vec[0]); // f takes a LPCSTR parameter
精彩评论