如何将long转换为LPCWSTR?

Vác*_*ych 1 c++ string type-conversion

如何在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();
}
Run Code Online (Sandbox Code Playgroud)

sbi*_*sbi 5

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

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

如果您有需要的API LPCWSTR,您可以使用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());
}
Run Code Online (Sandbox Code Playgroud)