How do I prevent buffer overflow converting a double to char?

Posted by Tommy on Stack Overflow See other posts from Stack Overflow or by Tommy
Published on 2010-05-12T00:10:37Z Indexed on 2010/05/12 0:14 UTC
Read the original article Hit count: 166

Filed under:
|
|

I'm converting a double to a char string:

char txt[10];
double num;

num = 45.344322345

sprintf(txt, "%.1f", num);

and using ".1f" to truncate the decimal places, to the tenths digit.
i.e. - txt contains 45.3

I usually use precision in sprintf to ensure the char buffer is not overflowed. How can I do that here also truncating the decimal, without using snprintf?

(i.e. if num = 345694876345.3 for some reason)

Thanks

© Stack Overflow or respective owner

Related posts about c

    Related posts about string