How to convert a char to an integer?

2

Converting a string to an integer with the atoi() function is easy, is not it?

However, when I use the atoi() function to convert a character to an integer, the program that is at runtime simply crashes.

What would be the best way to transform a character (eg '1') into an integer (ex: 1)?

    
asked by anonymous 01.04.2018 / 23:53

4 answers

1
 char c = '1';
int a = c - '0';

Do not forget to subtract

    
01.04.2018 / 23:58
7
  

Converting a string to an integer with the atoi() function is easy, is not 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 before, unless you can guarantee it to be.

#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 running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

    
01.04.2018 / 23:58
0

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.
    
02.04.2018 / 00:10
0

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;
    
02.04.2018 / 00:19