c++ - How to convert from int to wchar_t*? -


i did this:

static wchar_t* convert1(tdword data)  {   wchar_t result[10];   swprintf(result, sizeof(result) / sizeof(*result), l"%d", data);   wprintf(l"[%ls]\n", result);   return result; } 

and didn't work, guess because of stack memory has been cleared after return (could explain me why?). tried this:

static wchar_t* convert2(tdword data)  {   wchar_t* result = (wchar_t*)malloc(sizeof(wchar_t) * 10);   swprintf(result, sizeof(result) / sizeof(*result), l"%d", data);   wprintf(l"[%ls]\n", result);   return result; } 

and works, first digit of number, , not whole number. how right way ?

consider using string stream , by-val wstring, such as:

#include <iostream> #include <sstream> #include <string> #include <cstdint> using namespace std;  typedef uint32_t tdword;  static std::wstring convert1(tdword data) {     std::wostringstream os;     os << data;     return os.str(); }  int main(int argc, char *argv[]) {     tdword dwtest = 1024;     std::wstring res = convert1(dwtest);     std::wcout << res << std::endl;     return exit_success; } 

output

1024 

sorry had fake typedef. hope close using. major benefit of doing memory management, conversion, etc, handled library, having hand-roll near-nothing on side.


Comments