A char in C is already a number (the character's ASCII code), no conversion required.
If you want to convert a digit to the corresponding character, you can simply add '0':
Use with AIc = i +'0';
The '0' is a character in the ASCll table.
Answer from Ofir on Stack OverflowA char in C is already a number (the character's ASCII code), no conversion required.
If you want to convert a digit to the corresponding character, you can simply add '0':
Use with AIc = i +'0';
The '0' is a character in the ASCll table.
You can try atoi() library function. Also sscanf() and sprintf() would help.
Here is a small example to show converting integer to character string:
Use with AImain()
{
int i = 247593;
char str[10];
sprintf(str, "%d", i);
// Now str contains the integer as characters
}
Here for another Example
Use with AI#include <stdio.h>
int main(void)
{
char text[] = "StringX";
int digit;
for (digit = 0; digit < 10; ++digit)
{
text[6] = digit + '0';
puts(text);
}
return 0;
}
/* my output
String0
String1
String2
String3
String4
String5
String6
String7
String8
String9
*/
char* istr(int x) {
char* snum[100];
sprintf(snum, "%d", x);
return snum;
}Depends on what you want to do:
to read the value as an ascii code, you can write
char a = 'a';
int ia = (int)a;
/* note that the int cast is not necessary -- int ia = a would suffice */
to convert the character '0' -> 0, '1' -> 1, etc, you can write
char a = '4';
int ia = a - '0';
/* check here if ia is bounded by 0 and 9 */
Explanation:
a - '0' is equivalent to ((int)a) - ((int)'0'), which means the ascii values of the characters are subtracted from each other. Since 0 comes directly before 1 in the ascii table (and so on until 9), the difference between the two gives the number that the character a represents.
Well, in ASCII code, the numbers (digits) start from 48. All you need to do is:
int x = (int)character - 48;
Or, since the character '0' has the ASCII code of 48, you can just write:
int x = character - '0'; // The (int) cast is not necessary.
I want to convert an integer to something that I can pass to strcat, something like:
int number = 12; strcat(someString, intToString(number));
How do I do this?