views:

366

answers:

2

Hi, how can I convert long to LPCWSTR in C++? I need function similar to this one:

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

That function doesn't work because wnum.c_str() points to memory which is freed when wnum is destroyed when the function returns.

You need to take a copy of the string before you return it, i.e.

return wcsdup(wnum.c_str());

and then when you've finished using the result you need to free it, i.e.

LPCWSTR str = ToString(123);
// use it
free(str);
atomice
+3  A: 

Your function is named "to string", and it's indeed easier (and more universal) to convert to a string than to convert "to LPCWSTR":

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

If you have an API that needs a LPCWSTR, you can use 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());
}
sbi
It works nicely. Thanks a lot.
vasek7