Search code examples
c++stdstringlpcstr

convert std::string to LPCSTR with trailing or leading '\0'


How can I convert std::string to LPCSTR while preserving '\0' characters?

I want to use the result on OPENFILENAME.lpstrFilter which requires the filter to contain '\0' as delimiters.

std::string.c_str() seems to strip and trim '\0'

Thanks in advance!

==========================

(How do I properly add a comment to the responses like a reply post in a forum?)

After reading your comments, I went on to double check this snippet:

std::string filter = "Terrain Configuration (*.tcfg)\0*.tcfg\0\0";
const char* f1 = "Terrain Configuration (*.tcfg)\0*.tcfg\0\0";
const char* f2 = filter.c_str();
for(int i = 0; i < 50; i++)
{
 char c1 = *(f1 + i); // works
 char c2 = *(f2 + i); // doesn't work. beyond the first \0, it's garbage.
}

Am I mistaken on how c_str() or LPCSTR works?


Solution

  • C_STR doesn't strip the NUL characters. The error is likely in the way you are constructing the STD::string.