How to convert "pointer to const TCHAR" to "std :: string"?

I have a class that returns a typed pointer to "const TCHAR". I need to convert it to std :: string, but I have not found a way to do this.

Can someone give an idea on how to convert it?

+4
source share
4 answers

Depending on your compilation options, TCHAR is either char or WCHAR (or wchar_t ).

If you use a multibyte character string setting, then your TCHAR same as char. Therefore, you can simply set the string to the returned TCHAR* .

If you use character string customization in Unicode, then your TCHAR is a wide char and needs to be converted using WideCharToMultiByte .

If you are using Visual Studio, as I assume, you can change this setting in the project properties in the Character Set section.

+10
source

Do whatever Brian says. Once you get it into the code page you need, you can do:

 std::string s(myTchar, myTchar+length); 

or

 std::wstring s(myTchar, myTchar+length); 

to get it in line.

+3
source

You can also use convenient ATL text conversion macros for this, for example:

 std::wstring str = CT2W(_T("A TCHAR string")); 

CT2W = Const Text To Wide.

You can also specify a code page for conversion, for example

 std::wstring str = CT2W(_T("A TCHAR string"), CP_SOMECODEPAGE); 

These macros (in their current form) were available for Visual Studio C ++ projects with VS2005.

+3
source

It depends. If you have not defined _UNICODE or UNICODE , you can create a string containing this character, like this:

 const TCHAR example = _T('Q'); std::string mystring(1, example); 

If you use _UNICODE and UNICODE , then this approach may work, but the character cannot be converted to char . In this case, you will need to convert the character to a string. Usually you need to use a call like wcstombs or WideCharToMultiByte , which gives you more control over the encoding.

In any case, you will need to allocate a buffer for the result and build std::string from this buffer, not forgetting to free the buffer after completion (or use something like vector<char> to make this happen automatically).

+1
source

Source: https://habr.com/ru/post/1299465/


All Articles