Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an int to string in C?

Tags:

c

string

integer

How do you convert an int (integer) to a string? I'm trying to make a function that converts the data of a struct into a string to save it in a file.

like image 359
user1063999 Avatar asked Nov 24 '11 13:11

user1063999


People also ask

Can I 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.

How can I convert a number to a string in C?

Solution: Use sprintf() function. You can also write your own function using ASCII values of numbers.

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.


1 Answers

You can use sprintf to do it, or maybe snprintf if you have it:

char str[ENOUGH]; sprintf(str, "%d", 42); 

Where the number of characters (plus terminating char) in the str can be calculated using:

(int)((ceil(log10(num))+1)*sizeof(char)) 
like image 169
cnicutar Avatar answered Oct 15 '22 19:10

cnicutar