【问题标题】:How to convert long to LPCWSTR?如何将 long 转换为 LPCWSTR?
【发布时间】:2009-10-15 14:26:28
【问题描述】:

如何在 C++ 中将 long 转换为 LPCWSTR?我需要类似这个的功能:

LPCWSTR ToString(long num) {
    wchar_t snum;
    swprintf_s( &snum, 8, L"%l", num);
    std::wstring wnum = snum;
    return wnum.c_str();
}

【问题讨论】:

    标签: c++ string type-conversion


    【解决方案1】:

    您的函数被命名为“to string”,转换为字符串确实比转换“to LPCWSTR”更容易(也更通用):

    template< typename OStreamable >
    std::wstring to_string(const OStreamable& obj)
    {
      std::wostringstream woss;
      woss << obj;
      if(!woss) throw "dammit!";
      return woss.str();
    }
    

    如果你有一个需要LPCWSTR的API,你可以使用std::wstring::c_str()

    void c_api_func(LPCWSTR);
    
    void f(long l)
    {
      const std::wstring& str = to_string(l);
      c_api_func(str.c_str());
      // or 
      c_api_func(to_string(l).c_str());
    }
    

    【讨论】:

      【解决方案2】:

      该函数不起作用,因为 wnum.c_str() 指向在函数返回时销毁 wnum 时释放的内存。

      您需要在返回之前获取字符串的副本,即

      return wcsdup(wnum.c_str());
      

      然后当你使用完结果后你需要释放它,即

      LPCWSTR str = ToString(123);
      // use it
      free(str);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-13
        • 1970-01-01
        • 2011-11-13
        • 2013-05-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多