How to convert from LPCTSTR to std :: string?

I have LPCTSTRand you want to call a function that takes a parameter std::string.

What conversion needs to be done?

+5
source share
7 answers

Iceberg tip

LPCTSTRit can be either a single-byte or a multi-byte string (depending on the constant UNICODEdetermined at compile time or not), while std::stringusers (including your function) usually use it to store a single-byte string.

You will need two conversions: one for LPCSTR(not UNICODEbuild) and one for LPCWSTR( UNICODEbuild). The first is simple:

std::string convert(LPCSTR str) {
    return std::string(str);
}

, WideCharToMultiByte. , char; CodePage. , CP_ACP.

: WideCharToMultiByte example

, , , . , , , 100% , .

std::string MBFromW(LPCWSTR pwsz, UINT cp) {
    int cch = WideCharToMultiByte(cp, 0, pwsz, -1, 0, 0, NULL, NULL);

    char* psz = new char[cch];

    WideCharToMultiByte(cp, 0, pwsz, -1, psz, cch, NULL, NULL);

    std::string st(psz);
    delete[] psz;

   return st;
}

Caveat emptor: - , , . , . . .

, std::string (, UTF8) - char, - .

, STL, std::string, , , , .

, , , , std::string - ​​ , UTF-8. " ", , .

+14

:

std::string s = CT2A( lpctstr );
+6

: ", , std::string std:: fstream:: open()"

, . tstring ( typedef std::basic_string<TCHAR> tstring). Windows, Unicode. , \User\<myusername\My Documents\, <myUserName> ANSI ( , !)

tstring, . - std::fstream.

+2

LPCTSTR - Windows, " const". , T, .

Unicode, const wchar_t*, . , - const char*, .

, - Unicode, LPCTSTR - const wchar_t*. std::string , . std::wstring , .

const wchar_t* const char*, , , wcstombs. ATL ( , atlconv.h) , , :

USES_CONVERSION;
const wchar_t* = L"Wide string";
std::string str = W2A(value);
+1

Pragmatic approach:

     LPCTSTR input;

     std::string s;

#ifdef UNICODE
     std::wstring w;
     w = input;
     s = std::string(w.begin(), w.end()); // magic here
#else
     s = input;
#endif

See other answers for great background files!

+1
source

This piece of code should convert from LPWSTR to char * / std :: string

LPWSTR input = L"whatever";
int cSize = WideCharToMultiByte (CP_ACP, 0, input, wcslen(input), NULL, 0, NULL, NULL);
std::string output(static_cast<size_t>(cSize), '\0');
WideCharToMultiByte (CP_ACP, 0, input, wcslen(input),
                       reinterpret_cast<char*>(&output[0]), cSize, NULL, NULL);

and this fragment should do the conversion from single-byte std :: string to LPWSTR

std::string input = "whatever";
//computing wchar size:
int wSize = MultiByteToWideChar (CP_ACP, 0, (LPCSTR) input.c_str (), -1, 0, 0);

//allocating memory for wchar:
LPWSTR output = new WCHAR[wSize];

//conversion from string to LPWSTR:
MultiByteToWideChar (CP_ACP, MB_PRECOMPOSED , (LPCSTR) input.c_str (), -1, output, wSize);
+1
source

I do not know if this solution will help .

0
source

All Articles