How to turn a character into an integer in C?

Asked

Viewed 2,791 times

3

How to turn a character into an integer?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{
 char N[11];
 int i;
 scanf("%s",N);
 int cont = strlen(N);

 for(i=0; i<cont; i++)
    { 
     int valor = atoi(N[i]); // Só serve para um conjunto de caracteres
     if (valor >= 9)
        printf("%d",valor-9);
     else
         printf("%c",N[i]);
    }
    printf("\n");

 return (0);
}

2 answers

3


C strings, implemented as char array, are actually not "text" - they are only strings of 1 byte numbers (the char type). What causes these numbers to be interpreted as text is just the functions of the standard library - atoi, printf, strlen, etc... all expect a char pointer - a memory address, from which you will run the byte at that address and at the following addresses, interpreting these bytes as characters, until reaching a byte with value "0".

To be clear, a "char" element in C is a number, between -128 and +127 - that "fits" in a single byte. The language syntax allows the value of this number to be written numerically, or as a character, between single quotes (in this case, the element between single quotes must be part of the ASCII table, or using a Sequence escape such as ' n', 'xff', etc...). Also, if you’re working with numeric byte values, it’s generally worth working with the type unsigned char, with numbers between 0 and 255.

In other words:

... 
char a = '0';
printf('%d', (int) a); 
...

It will print the code of character '0', which is 48. While:

... 
char a = '0';
printf('%c', a); 
...

will print the '0' character as it is: the difference is not in the value contained in the 'a' variable, but rather in how the printf will use this value - and this use is defined by string formatting. Use of cast (int) in the first example is just to ensure that the compiler will put the value of 'a' using the integer size (usually 4 bytes) in the stack - otherwise the printf’s '%d" could consume 4 bytes where there would be only 1 byte - the 'a' passed as (char) and cause a "Stackunderflow"#- vulgo, stack burst.

So, in your code, the biggest problem is you calling the atoi, which expects a memory address for a char sequence, which it will interpret as text, and you pass instead a single number. In this case, the compiler will issue a Warning, but by default, it will generate the code, treating its character, a number between -128 and 127, as a memory address. When trying to read this "memory address", the code within the atoi function will not be authorized by the operating system, since these addresses are not part of the memory part with data addressable by your program, and an access violation occurs, which is reported by the operating system as a "Segmentation Fault".

Finally, responding by looking at your code:

If you simply subtract the code from the character '0' of each character of the input string as a string, it will have the numeric value of the digit:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{
 char N[100];  // não tem por que usar um valor pequeno aqui (veja texto abaixo) (*)

 int i;
 scanf("%s",N);
 int cont = strlen(N);

 for(i=0; i<cont; i++)
    { 
     int valor = N(i) - '0'; // Subtrai o valor do código de '0' (48) do carácter digitado;
     if (valor >= 0 && valor > 9)
        {
         printf("Dígito %d \n", valor);
        }
     else
        {
         printf("Caráctere %c \n",N[i]);
        }
    }

 return (0);
}

(*) About 100 instead of 11 for the array: if the user type a few more characters it causes a bufferoverflow and unpredictable results. N the truth, 'scanf' should be avoided as a whole in production code - see: https://stackoverflow.com/questions/1621394/how-to-prevent-scanf-causing-a-buffer-overflow-in-c

1

Can use a cast, example:

char c='a';
printf("%d", (int) c);

tutorialspoint

To convert the character '0' -> 0, '1' -> 1, etc

char c = '5';
int i = c - '0';
  • 1

    Usually yes, and you can signal, too, so other people close, until you gain the privilege of voting or even closing on your own.

Browser other questions tagged

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