将 const char\* 转换为 const wchar_t\*

新手上路,请多包涵

我正在尝试使用 Irrlicht 创建一个程序,该程序从用 Lua 编写的配置文件中加载某些内容,其中之一是窗口标题。 However, the lua_tostring function returns a const char* while the Irrlicht device’s method setWindowCaption expects a const wchar_t* .如何转换 lua_tostring 返回的字符串?

原文由 Giaphage47 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 935
1 个回答

SO上有多个问题可以解决Windows上的问题。示例帖子:

  1. char* 到 const wchar_t * 的转换
  2. 从 unsigned char* 转换为 const wchar_t*

http://ubuntuforums.org/showthread.php?t=1579640 上发布了一个与平台无关的方法。本站出处为(希望没有侵犯版权):

 #include <locale>
#include <iostream>
#include <string>
#include <sstream>
using namespace std ;

wstring widen( const string& str )
{
    wostringstream wstm ;
    const ctype<wchar_t>& ctfacet = use_facet<ctype<wchar_t>>(wstm.getloc()) ;
    for( size_t i=0 ; i<str.size() ; ++i )
              wstm << ctfacet.widen( str[i] ) ;
    return wstm.str() ;
}

string narrow( const wstring& str )
{
    ostringstream stm ;

    // Incorrect code from the link
    // const ctype<char>& ctfacet = use_facet<ctype<char>>(stm.getloc());

    // Correct code.
    const ctype<wchar_t>& ctfacet = use_facet<ctype<wchar_t>>(stm.getloc());

    for( size_t i=0 ; i<str.size() ; ++i )
                  stm << ctfacet.narrow( str[i], 0 ) ;
    return stm.str() ;
}

int main()
{
  {
    const char* cstr = "abcdefghijkl" ;
    const wchar_t* wcstr = widen(cstr).c_str() ;
    wcout << wcstr << L'\n' ;
  }
  {
    const wchar_t* wcstr = L"mnopqrstuvwx" ;
    const char* cstr = narrow(wcstr).c_str() ;
    cout << cstr << '\n' ;
  }
}

原文由 R Sahu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题