I am using the itoa() function to convert an int into string, but it is giving an error:
undefined reference to `itoa' collect2: ld returned 1 exit status What is the reason? Is there some other way to perform this conversion?
sprintf() Function to Convert an Integer to a String in C As its name suggests, it prints any value into a string. This function gives an easy way to convert an integer to a string. It works the same as the printf() function, but it does not print a value directly on the console but returns a formatted string.
The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.
The itoa() function coverts the integer n into a character string. The string is placed in the buffer passed, which must be large enough to hold the output. The radix values can be OCTAL, DECIMAL, or HEX.
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.
Use snprintf - it is standard an available in every compilator. Query it for the size needed by calling it with NULL, 0 parameters. Allocate one character more for null at the end.
int length = snprintf( NULL, 0, "%d", x ); char* str = malloc( length + 1 ); snprintf( str, length + 1, "%d", x ); ... free(str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With