Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting int to string in C

Tags:

c

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?

like image 618
Shweta Avatar asked Mar 09 '11 07:03

Shweta


People also ask

Can we convert int to string in C?

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.

What is atoi () in C?

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.

What is ITOA in C?

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.


2 Answers

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.

like image 130
Edwin Buck Avatar answered Oct 02 '22 18:10

Edwin Buck


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); 
like image 21
user2622016 Avatar answered Oct 02 '22 18:10

user2622016