1

Is there a way to convert the above?

If so what is 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.

Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
  • Any reason using a vector instead of a string ? http://stackoverflow.com/questions/1200188/how-to-convert-stdstring-to-lpcstr – DumbCoder Jul 19 '10 at 09:40
  • @DumbCoder: see this question and the first comment of GMan for the reason: http://stackoverflow.com/questions/3279733/ofstream-doesnt-write-buffer-to-file – ereOn Jul 19 '10 at 09:43
  • It's inside a variadic function, using vsprintf, don't know if strings are usable here... – Tony The Lion Jul 19 '10 at 09:52
  • Are you sure you need `LPCSTR`? The 8-bit string datatypes in Windows are obsolete and deprecated; use the UTF-16 string types like `LPCWSTR` instead. – Philipp Jul 19 '10 at 10:01

4 Answers4

3
std::string s(vec.begin(), vec.end());
// now use s.c_str()

I think this should be fairly safe.

jA_cOp
  • 3,275
  • 19
  • 15
  • 1
    maybe use the two-iterator constructor `s(vec.begin(), vec.end())` instead? Seems to be a bit more idiomatic. – Philipp Jul 19 '10 at 09:58
1

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*).

ereOn
  • 53,676
  • 39
  • 161
  • 238
0

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.

Aamir
  • 14,882
  • 6
  • 45
  • 69
  • 1
    Only the constructor that doesn't take a size parameter requires the string to be null-terminated. – jA_cOp Jul 19 '10 at 09:49
0

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
Philipp
  • 48,066
  • 12
  • 84
  • 109
  • 1
    Also, the memory can move around whenever more memory is reserved, so you'd have to make sure the vector isn't manipulated while the pointer exists. – jA_cOp Jul 19 '10 at 10:07