How can I copy the ASCII value to an int in C?

2

For example, having the following code my intention is to operate to obtain an index number

#include <stdio.h>
#include <string.h>
int main(void) {
 char mes[2]= {"02"};
 int numero;
 numero = (int)mes;
    char *strings[]={ "Ene", "Feb", "Mar", "Abr", "May", "Jun","Jul", "Ago", "Sep","Oct", "Nov", "Dic"};

  printf("%s\n", strings[numero - 1]);   

    return 0;
}

in the example you should print Feb

    
asked by Bubblegum Crisis 22.10.2017 в 06:19
source

1 answer

3

Well, use the function atoi( ) (of <stdlib.h> ), which is responsible for precisely that: interprets the content of a string and returns a int .

However, you have to modify your code, since atoi( ) expects a string ending in 0 :

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

int main( void ) {
  char *mes= "02"; // <-- Cambiamos esto.
  int numero;

  numero = atoi( mes );

  char *strings[]={ "Ene", "Feb", "Mar", "Abr", "May", "Jun","Jul", "Ago", "Sep","Oct", "Nov", "Dic"};

  printf( "%s\n", strings[numero - 1] );   

  return 0;
}

Compiling and executing it, we obtain the desired output:

  

Feb

This function is not the secure , since we can not check for possible errors ; for example,

atoi( "aa" );

We would return a 0 .

You have similar but more powerful features, such as strtol( ) and strtoll( ) , with return values long int and long long int respectively, with support for different numerical bases and that allow us to detect errors during the interpretation.

    
answered by 22.10.2017 / 08:15
source