# Thread: Is there a way to convert a char?

1. ## Is there a way to convert a char?

Hi, I am with a doubt that i have since yesterday, is there a way to transform a char value to an int value, for example, 2x, i want to get the two, but it is declared as a char, so i do:
a=2
b=x

after that, being "a" also a char value, is there a function that let me change it to an int?

thanks

2. I believe atoi() does the trick.

but char and int is (relatively) the same thing.

Try: printf("%d", 'A'); or printf("%c", 65);

www.asciitable.com shows all the integer values for each character, and if you want, you could make a function that converts a character to your own specified integer based off those values.

3. I'm gathering you want something like:
Code:
```char a = '1';
int b = 1;
/* do something */
/* a == b is now true */```
If thats what you want you can subtract the value of '0' from a
Code:
```char a = '1';
int b = 1;
a -= '0';
/* now a == b */```
I believe it's been stated that the values of '0' - '9' must be in ascending sequentical values.

4. Code:
```#include <stdlib.h>

int main()
{
char ch[2];
int i;

strcpy(ch, "2x");

ch[1] = '\0';

i = atoi(ch);

printf("%c	-	%d", ch[0], i);

return 0;
}```
One way to do it.... easy to understand.

5. Originally Posted by dagdarian
Code:
```#include <stdlib.h>

int main()
{
char ch[2];
int i;

strcpy(ch, "2x");

ch[1] = '\0';

i = atoi(ch);

printf("%c	-	%d", ch[0], i);

return 0;
}```
1) No need to use strcpy as you could easily initalize the array with the values
2) should be int main(void) if you aren't using command line arguements
3) Please don't provide the full solution if the OP hasn't provided any code of their own.
One way to do it.... easy to understand.

6. The code is valid for example purposes,

strcpy was used on the assumtion that "2x" wasn't a predefined string and to show that the original character string did not have to be altered to use this method. Leaving open the option that ch could simply be a temporary variable (i.e. for use in a function)

7. Originally Posted by dagdarian
The code is valid for example purposes,

strcpy was used on the assumtion that "2x" wasn't a predefined string and to show that the original character string did not have to be altered to use this method. Leaving open the option that ch could simply be a temporary variable (i.e. for use in a function)
But it's not valid. The strcpy() copies three chars to a two-char array:

'2', 'x', 0

Also, you should #include <string.h> to use strcpy(). (And #include <stdio.h> to use printf().)

Regards,

Dave

8. hmm... why not just use sscanf()?
Code:
```char szStr[] = "123abc";
int a;

sscanf(szStr, "%d", &a); // Will read 123 into a```

Popular pages Recent additions