Float to String Conversion

Whatever the size of buff, it always show 8 characters.why? how much size is allocated to buff ?? 2 bytes ? If we take one character of one byte than it should only store 0. in buffer .. what's happening here ?
1
2
3
float n = 0.5;
char buff[2];
    sprintf(buff, "%f", n);
As I mentioned in the other post, buff is being overwritten.

If you're using C, you should be doing:
1
2
3
float n = 0.5;
char buff[20];
snprintf(buff, sizeof(buff), "%f", n);

If you're using C++11, you can do:
1
2
float n = 0.5;
std::string buff = std::to_string(n);
Last edited on
but for first code it shows correct output ? why ? size of buffer is small still showing same output ...
The output appears ok, but you've overwritten the following memory. You don't know what's there, so you don't know what problems you've caused.
std::to_string

by the dark lord! i didnt know this existed! cheers kbw.
Topic archived. No new replies allowed.