How to convert wchar_t** to char**?

我的梦境 提交于 2019-12-07 08:47:49

问题


I get argv as wchar_t** (see below), because I need to work with unicode, but I need to convert it to char **. How can I do that?

int wmain(int argc, wchar_t** argv) 
{ 

回答1:


There is more than one way to do this. Depending on your environment and available compiler/standard library/other libraries, you have at least three choices:

  1. Use std::locale and std::codecvt<> facet;
  2. use C locale functions like std::mbstowcs();
  3. use 3rd party functions like iconv() on *nix or WideCharToMultiByte() on Windows.

Do you really need to do the conversion?

You should realise that often (especially on Windows) the conversion from wchar_t string to char string is a lossy conversion. The character set used by system for char strings is often not UTF-8. E.g. if you convert a file name with national characters or in some Asian language to char string you are most likely going to get something that will not be really usable to access the original file.




回答2:


This does the trick:

#define MAXLEN 512
   char tx[MAXLEN];
   mbstowcs(argv[i], tx, MAXLEN);



回答3:


Why do you need to convert? In most of the cases you need to change your project settings, so everything accepts wide chars. If a third party library wants non-Unicode string, then you need to recompile it with the proper options for Unicode. If there are no proper options for Unicode, I would get rid of this library and find (write) a better one.



来源:https://stackoverflow.com/questions/3227270/how-to-convert-wchar-t-to-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!