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)?

Author: Bacco, 2018-04-01

4 answers

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

Do not forget the subtraction

 2
Author: FourZeroFive, 2018-04-01 21:58:41

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 .

 7
Author: Maniero, 2020-07-16 14:50:59

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.
 0
Author: Felipe Morschel, 2018-04-01 22:10:07

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;
 0
Author: Ricardo Takemura, 2018-04-01 22:19:32