If you have an int or float, how can you cast it to a wchar_t* without using external libraries like boost?
views:
138answers:
4You can't cast it meaningfully:
int x = 43;
wchar_t *ptr = reinterpret_cast<wchar_t *>(x);
This will compile, but it has no meaning. It simply re-interprets the integer value and forces the creation of a pointer with that value. Since there is nothing valid for you access at the address, it is meaningless and useless.
If you mean "convert", there is probably a wide-character version of snprintf() you can use, e.g. snwprintf() or similar. This might depend a bit on your platform.
It's not exactly casting, but I suspect you want to have a string representation. printf-family functions or stringstreams may be of help. Why would you want to cast it to wchar_t is beyond me.
std::wostringstream oss;
int i = 1212; // or float f = 1212.0f;
oss<<i; // oss<<f;
std::wstring ws = oss.str();
const wchar_t* cwp = ws.c_str(); // const wchar_t*
std::vector<wchar_t> buf( cwp , cwp + (wc.size() + 1) );
wchar_t* wp = &buf[0]; // wchar_t*
You can do it this way, in conjunction to hacker's answer above
int num1 = 25; float fnum1 = 3.14; char buf[50]; sprintf(buf, "Int: %d. Float: %4.2f", num1, fnum1);
The only thing you have to be careful is to ensure you have enough sufficient space in the buffer for the sprintf function to work, otherwise you will get an overflow and corrupt another area of memory which will crash your program.
Hope this helps, Best regards, Tom.