Convert numbers with toString in Ansi C
Is it开发者_StackOverflow社区 possible to use toString operator, or how to convert numbers to char arrays.
int myNumber = 27; /* or what have you */
char myBuffer[100];
snprintf(myBuffer, 100, "%d", myNumber);
There are several considerations for you to think about here. Who provides the memory to hold the string? How long do you need it for, etc? (Above it's a stack buffer of 100 bytes, which is way bigger than necessary for any integer value being printed.)
Best answer: start using Java. Or Javascript, or C#, or for the love of God almost anything but C. Only tigers lie this way.
Use the sprintf()
function.
sprintf()
is considered unsafe because it can lead to a buffer overflow. If it's available (and on many platforms it is), you should use snprintf()
instead.
Consider the following code:
#include <stdio.h>
int main()
{
int i = 12345;
char buf[4];
sprintf(buf, "%d", i);
}
This leads to a buffer overflow. So, you have to over-allocate a buffer to the maximum size (as a string) of an int
, even if you require fewer characters, since you have the possibility of an overflow. Instead, if you used snprintf()
, you could specify the number of characters to write, and any more than that number would simply be truncated.
#include <stdio.h>
int main()
{
int i = 12345;
char buf[4];
snprintf(buf, 4, "%d", i);
//truncates the string to 123
}
Note that in either case, you should take care to allocate enough buffer space for any valid output. It's just that snprintf()
provides you with a safety net in case you haven't considered that one edge case where your buffer would otherwise overflow.
精彩评论