How do I convert wchar_t* to std::string?

2019-01-18 17:45发布

I changed my class to use std::string (based on the answer I got here but a function I have returns wchar_t *. How do I convert it to std::string?

I tried this:

std::string test = args.OptionArg();

but it says error C2440: 'initializing' : cannot convert from 'wchar_t *' to 'std::basic_string<_Elem,_Traits,_Ax>'

6条回答
虎瘦雄心在
2楼-- · 2019-01-18 18:12

Following code is more concise:

wchar_t wstr[500];
char string[500];
sprintf(string,"%ls",wstr);
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-18 18:19

This is an old question, but if it's the case you're not really seeking conversions but rather using the TCHAR stuff from Mircosoft to be able to build both ASCII and Unicode, you could recall that std::string is really

typedef std::basic_string<char> string

So we could define our own typedef, say

#include <string>
namespace magic {
typedef std::basic_string<TCHAR> string;
}

Then you could use magic::string with TCHAR, LPCTSTR, and so forth

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-18 18:24
wstring ws( args.OptionArg() );
string test( ws.begin(), ws.end() );
查看更多
女痞
5楼-- · 2019-01-18 18:27

just for fun :-):

const wchar_t* val = L"hello mfc";
std::string test((LPCTSTR)CString(val));
查看更多
你好瞎i
6楼-- · 2019-01-18 18:31

You can convert a wide char string to an ASCII string using the following function:

#include <locale>
#include <sstream>
#include <string>

std::string ToNarrow( const wchar_t *s, char dfault = '?', 
                      const std::locale& loc = std::locale() )
{
  std::ostringstream stm;

  while( *s != L'\0' ) {
    stm << std::use_facet< std::ctype<wchar_t> >( loc ).narrow( *s++, dfault );
  }
  return stm.str();
}

Be aware that this will just replace any wide character for which an equivalent ASCII character doesn't exist with the dfault parameter; it doesn't convert from UTF-16 to UTF-8. If you want to convert to UTF-8 use a library such as ICU.

查看更多
倾城 Initia
7楼-- · 2019-01-18 18:32

You could just use wstring and keep everything in Unicode

查看更多
登录 后发表回答