tags:

views:

138

answers:

4

If you have an int or float, how can you cast it to a wchar_t* without using external libraries like boost?

+4  A: 

You 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.

unwind
A: 

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.

Michael Krelin - hacker
+5  A: 
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*
OwnWaterloo
Oh, I'm sorry~ I will make it. Thanks~
OwnWaterloo
A: 

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.

tommieb75
By the way, why do you want to cast it to a type that has underlying type of char * family? Can you clarify a bit more in what you are trying to achieve exactly?
tommieb75
My XML classes handle things in wchar_t*. I have an integer that I'd like to write to my xml file.
Mark
@Mark: Writing an integer to a file is a far different thing from casting it to a pointer value.
David Thornley