***there was an implementation error in my previous post. edited to work properly***
this code also assumes that the size of long and int are the same. this is architecture and compiler dependant and not always true. additional checks need to be done if not.
Code:
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* some definitions */
char *str = "12345";
char *p;
long num;
char s[12]; /* '-2147483647\0' (this is the longest decimal string from a 32bit signed int */
/* convert a string to an int */
/*
DONT USE atoi(), it does not detect errors
num = atoi(str);
*/
errno = 0;
num = strtol(str, &p, 0);
if(p != '\0')
{
printf("error: invalid string\n");
return 1;
}
if(errno == ERANGE && (num == LONG_MIN || num == LONG_MAX))
{
printf("error: number outside range of signed long int\n");
return 1;
}
/* convert an int to a string */
snprintf(s, sizeof(s), "%d", (int)num);
printf ("the string is '%s'\n", s);
return 0;
}