简体   繁体   English

如何将“指向const TCHAR的指针”转换为“std :: string”?

[英]How do I convert a “pointer to const TCHAR” to a “std::string”?

I have a class which returns a typed pointer to a "const TCHAR". 我有一个类,它返回一个指向“const TCHAR”的类型指针。 I need to convert it to a std::string but I have not found a way to make this happen. 我需要将它转换为std :: string但我还没有找到一种方法来实现这一点。

Can anyone provide some insight on how to convert it? 谁能提供一些有关如何转换它的见解?

Depending on your compiling settings, TCHAR is either a char or a WCHAR (or wchar_t ). 根据您的编译设置, TCHAR可以是charWCHAR (或wchar_t )。

If you are using the multi byte character string setting, then your TCHAR is the same as a char. 如果使用多字节字符串设置,则TCHAR与char相同。 So you can just set your string to the TCHAR* returned. 所以你可以将你的字符串设置为返回的TCHAR*

If you are using the unicode character string setting, then your TCHAR is a wide char and needs to be converted using WideCharToMultiByte . 如果您使用的是unicode字符串设置,那么您的TCHAR是一个宽字符,需要使用WideCharToMultiByte进行转换。

If you are using Visual Studio, which I assume you are, you can change this setting in the project properties under Character Set. 如果您使用的是我认为的Visual Studio,则可以在“字符集”下的项目属性中更改此设置。

Do everything Brian says. 做一切Brian说的。 Once you get it in the codepage you need, then you can do: 一旦你在你需要的代码页中得到它,你就可以:

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

or 要么

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

to get it into a string. 把它变成一个字符串。

You can also use the handy ATL text conversion macros for this, eg: 您还可以使用方便的ATL文本转换宏,例如:

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

CT2W = Const Text To Wide. CT2W = Const文本到宽。

You can also specify a code page for the conversion, eg 您还可以指定转换的代码页,例如

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

These macros (in their current form) have been available to Visual Studio C++ projects since VS2005. 自VS2005以来,这些宏(以其当前形式)可用于Visual Studio C ++项目。

It depends. 这取决于。 If you haven't defined _UNICODE or UNICODE then you can make a string containing the character like this: 如果您尚未定义_UNICODEUNICODE那么您可以创建一个包含如下字符的字符串:

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

If you have are using _UNICODE and UNICODE then this approach may still work but the character may not be convertable to a char . 如果您正在使用_UNICODEUNICODE则此方法可能仍然有效,但该字符可能无法转换为char In this case you will need to convert the character to a string. 在这种情况下,您需要将字符转换为字符串。 Typically you need to use a call like wcstombs or WideCharToMultiByte which gives you fuller control over the encoding. 通常,您需要使用wcstombsWideCharToMultiByte等调用,以便更全面地控制编码。

Either way you will need to allocate a buffer for the result and construct the std::string from this buffer, remembering to deallocate the buffer once you're done (or use something like vector<char> so that this happens automatically). 无论哪种方式,您都需要为结果分配缓冲区并从此缓冲区构造std::string ,记住在完成后释放缓冲区(或者使用vector<char>类的东西,以便自动发生)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM