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))
Answer from cnicutar on Stack OverflowYou 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))
As pointed out in a comment, itoa() is not a standard, so better use the sprintf() approach suggested in the rival answer!
You can use the itoa() function to convert your integer value to a string.
Here is an example:
int num = 321;
char snum[5];
// Convert 123 to string [buf]
itoa(num, snum, 10);
// Print our string
printf("%s\n", snum);
If you want to output your structure into a file there isn't any need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.
But not using ascii. if i give "56", it has to return 56 in int format
Beginner needing help, converting string to integer.
How to convert integer to string in C?
is there any function in c to convert an integer to a string?
Converting an int to a string
Can I convert string to integer in C without using atoi function?
Can we convert floating-point strings to integers directly in C?
Which header file is required for using the atoi() function?
Videos
Hello, I'm a first year CS student and am learning c++ at my university. I need to build a function that inputs a string from the user, "1234" for example, and then return the integer 1234.
I am not allowed to use the stoi function, and <iostream> and <string> are the only allowed libraries. I'm at a wall, I would appreciate any help! Thanks.