以下代码将“失败”打印到控制台:
#include "stdafx.h"
#include <locale>
#include <memory>
#include <string>
#include <cstring>
#include <iostream>
int main(int argc, char* argv[])
{
typedef std::codecvt<wchar_t, char, mbstate_t> cvt;
// string to convert
const char cstr[] = "тест";
size_t sz = std::strlen(cstr);
mbstate_t state;
const char *cnext;
wchar_t *wnext;
// buffer to write
wchar_t *buffer = new wchar_t[sz + 1];
std::uninitialized_fill(buffer, buffer + sz + 1, 0);
// converting char* to wchar*, using locale
cvt::result res;
std::locale l(std::locale("Russian_Russia.1251"));
res = std::use_facet<cvt>(l).in(state,
cstr, cstr + sz, cnext,
buffer, buffer + sz + 1, wnext);
if(res == cvt::error)
std::wcout << L"failed" << std::endl;
else
std::wcout << buffer << std::wcout;
delete [] buffer;
return 0;
}
我查看了源代码,发现函数 in() 失败,因为函数_Mbrtowc (wmbtowc.c) 返回 -1:
if (___mb_cur_max_l_func(locale) <= 1 ||
(MultiByteToWideChar(codepage,
MB_PRECOMPOSED|MB_ERR_INVALID_CHARS,
(char *)pst,
2,
pwc,
(pwc) ? 1 : 0) == 0))
{ /* translation failed */
*pst = 0;
errno = EILSEQ;
return -1;
}
因为___mb_cur_max_l_func() (initctyp.c) 为 Russian_Russa.1251 语言环境返回 1。这是什么意思?我认为这是不正常的,codecvt 无法将 char* 转换为 wchar_t*。