Shweta Shweta - 3 years ago 144
C Question

Converting int to string in c

I am using the

function to convert an
but it is giving an error

undefined reference to `itoa'
collect2: ld returned 1 exit status

Can someone tell me the reason?
Is there some other way to perform this conversion?

Answer Source

Use snprintf, it is more portable than itoa.

itoa is not part of standard C, nor is it part of standard C++; but, a lot of compilers and associated libraries support it.

Example of sprintf

char* buffer = ... allocate a buffer ...
int value = 4564;
sprintf(buffer, "%d", value);

Example of snprintf

char buffer[10];
int value = 234452;
snprintf(buffer, 10, "%d", value);

Both functions are similar to fprintf, but output is written into an array rather than to a stream. The difference between sprintf and snprintf is that snprintf guarantees no buffer overrun by writing up to a maximum number of characters that can be stored in the buffer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download