How to convert a char to an integer?

Asked

Viewed 25,657 times

1

Convert a string for an integer with the function atoi() it’s easy, it’s not even?

However, when I use the function atoi() to convert a character to an entire program that is running time simply ends up crashing.

What would be the best way to transform a character (e.g., '1') into an integer (e.g.:1)?

  • https://answall.com/questions/3760/o-que-acontecem-uma-convers%C3%A3o-de-um-char-para-um-int

4 answers

8

Convert a string to an integer with the function atoi() it’s easy, it’s not even?

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 that 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
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • there is some other function Maniero

  • 4

    Ready-made.

3


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

Don’t forget the subtraction

1

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.

1

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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.