How to convert a char to an integer?
Converting a string
to an integer with the function atoi()
is easy, isn't it?
However, when I use the function atoi()
to convert a character to an integer the program that is at runtime simply crashes.
What would be the best way to turn a character (ex: '1') into an integer (ex: 1)?
4 answers
char c = '1';
int a = c - '0';
Do not forget the subtraction
Converting a string to an integer with the function
atoi()
is easy, isn't it?
No, this function is considered problematic and should not be used.
For what you want just do:
caractere - '0'
Where caractere
is the variable that has the char
you want to convert.
Of course it would be good for you to check if the character is a digit first, unless you can guarantee it is.
#include <stdio.h>
int main(void) {
char c = '1';
printf("%d", (c - '0') + 1); // + 1 só p/ mostrar que virou numérico mesmo e faz a soma
}
See working on ideone. And no repl.it. also I put on GitHub for future reference .
The strtol () function can solve your problem. Try something like this:
int num; \\Variável para armazenar o número em formato inteiro
char cNum[] = {0}; \\Variável para armazenar o número em formato de string
printf("Digite um numero: "); \\Pedindo o número ao usuário
scanf("%s%*c", cNum); \\Armazenando número em forma de string. O "%*c" serve para não acabar salvando "" (nada)
num = strtol(cNum, NULL, 10); \\Transformando para número inteiro de base 10
printf("%i", num); \\Mostrando na tela o número salvo.
I think you can do it like this:
char c = '1';
//se retornar -1 ele não é número
int v = (int) (c > 47 && c < 58) ? c - 48 : -1;