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.