2010-12-02 142 views
24

我改变了我的类中使用的std :: string(基于答案我有here而是一个功能我有回报的wchar_t *怎样将它转换为的std :: string如何将wchar_t *转换为std :: string? ?

我尝试这样做:

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

但它说错误C2440:初始化:不能从转换 '为wchar_t *' 到 '的std :: basic_string的< _Elem,_Traits,_AX>'

回答

8

你可以只使用wstring并保留一切以Unicode

+1

,我还是会得到一个const char *,如果我使用.c_str()?我有其他函数,期望const char * – codefrog 2010-12-02 21:16:58

+1

我将猜测你正在用Unicode编译你的项目,但实际上并不需要它。如果这是正确的,那么可以将项目的属性更改为不为Unicode编译,然后使用`string`。在项目属性,配置属性,常规,字符集中选中。你需要这个来说`使用多字节字符集`来摆脱Unicode到处。 – 2010-12-02 21:19:41

+0

本来我打算对某些部分使用Unicode,但后来我决定我会担心这一点。在这一点上,我只是为了让程序工作而烦恼。我使用SimpleINI和SimpleOpt来加载选项,并使用Unicode。我还使用另一个也使用Unicode的软件的SDK。全部禁用Unicode可能会使代码的这些部分停止工作。 – codefrog 2010-12-02 21:22:17

6

您可以使用下面的函数转换宽字符字符串转换为ASCII字符串:

#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(); 
} 

要知道,这将只是更换任何宽字符为其等效的ASCII字符不与dfault参数存在;它不会从UTF-16转换为UTF-8。如果你想转换为UTF-8使用库,如ICU

29
wstring ws(args.OptionArg()); 
string test(ws.begin(), ws.end()); 
5

这是一个老问题,但如果它是你没有真正寻求转换,而是使用TCHAR从东西向的Mircosoft能够建立两个ASCII和Unicode的情况下,你能记得的std ::字符串是真的

typedef std::basic_string<char> string 

因此,我们可以定义自己的typedef,说

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

那么你可以使用magic::stringTCHARLPCTSTR,等等

0

只是为了好玩:-):

const wchar_t* val = L"hello mfc"; 
std::string test((LPCTSTR)CString(val));