char *到const wchar_t *转换 [英] char* to const wchar_t * conversion

查看:301
本文介绍了char *到const wchar_t *转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将字符指针转换为w_char *,以便使用ParseNetworkString()。我已经尝试找到解决方案,我自己,虽然我找到一个解决方案,有一个问题,阻止我使用它:



b1naryatr0phy在另一篇文章:

  std :: wstring name(LSteve Nash); 
const wchar_t * szName = name.c_str();

这对我来说几乎是有效的,除了我不能只传递字符串显式性并不总是相同的,这意味着我不能把它在引号。如果我用一个函数调用替换参数,那么第一行给我一个错误(例如:std :: wstring name(LgetIpAddress());我试过std :: wstring name(L+ getIpAddress );,认为它只是需要一个引号在L后,但是不工作,任何建议?



谢谢!

链接到其他帖子: stackoverflow.com/questions/246806/i-want-to-convert-stdstring-into-a-const-wchar-t>我想将std :: string转换为const wchar_t *



PS对不起,只是为了澄清,getIpAddress返回一个字符指针

解决方案

getIpAddress / code>?



这是一个代码片段,显示如何将字符串转换为 wstring (使用标准C ++ 11,无错误检查):

  wstring to_wstring string const& str)
{
size_t len = mbstowcs(nullptr,& str [0],0);
if(len == -1)//无效的源str,throw
wstring wstr(len,0);
mbstowcs(& wstr [0],& str [0],wstr.size());
return wstr;
}


I need to convert character pointer to a w_char * in order to use ParseNetworkString(). I've tried finding solutions to this myself, and while I have found one solution, there is one issue which blocks me from using it:

b1naryatr0phy said in an other post:

std::wstring name( L"Steve Nash" );
const wchar_t* szName = name.c_str();

this almost works for me, except that I can't just pass the string explicity, as its value is not always going to be the same, meaning I can't just put it in quotes. If I replace the parameter with a function call, then the first line gives me an error (example: std::wstring name(LgetIpAddress()); I've tried std::wstring name(L" " + getIpAddress() + " "); , thinking that it just needs a quotation mark after the L, but that doesn't work either.. any suggestions?

Thanks! :)

Extra Kudos to whoever can answer this!

link to other post: I want to convert std::string into a const wchar_t *

P.S. Sorry, just to clarify, getIpAddress returns a character pointer

解决方案

What's the type of getIpAddress()?

Here's a snippet showing how to convert a string to a wstring (using standard C++11, no error checking):

wstring to_wstring(string const& str)
{
  size_t len = mbstowcs(nullptr, &str[0], 0);
  if (len == -1) // invalid source str, throw
  wstring wstr(len, 0);
  mbstowcs(&wstr[0], &str[0], wstr.size());
  return wstr;
}

这篇关于char *到const wchar_t *转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆