开发者

Cleaner way to convert from CStringW to std::string?

开发者 https://www.devze.com 2023-01-08 16:45 出处:网络
I figured out a somewhat convoluted way to convert a CStringW to a std::string, but I was wondering if there\'s 开发者_JAVA技巧a cleaner way than:

I figured out a somewhat convoluted way to convert a CStringW to a std::string, but I was wondering if there's 开发者_JAVA技巧a cleaner way than:

CStringW cwstr;
std::wstring stdwstr = cwstr;
std::string stdstr = CW2T(stdwstr.c_str());


You can cut out the intermediate std::wstring:

CStringW cwstr;
std::string stdstr = CW2A(cwstr);

Also note that you want the CW2A macro for correctness. CW2T converts to a TCHAR string, so the code you posted would only compile for an ANSI build (where TCHAR is char).


std::string str = CStringA( cwstr );

Job done.


std::string has the following constructor:

template<class InputIterator> string (InputIterator begin, InputIterator end);

So you could use it:

CStringW cwstr;
std::string x( &cwstr.GetString()[0], &cwstr.GetString()[cwstr.GetLength()] );

Implicit convertion wchar_t to char will take place.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号