convert.c
/**
* Demonstrates the difference between atoi() and strtol(). If possible, use
* strtol so you can check for conversion errors.
*/
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *str = "University of San Francisco";
int i = atoi(str);
printf("%d\n", i);
char *endptr;
long j = strtol(str, &endptr, 10);
if (endptr == str) {
printf("Unconvertable! (Is that a word?)\n");
perror("strtol");
}
if (j <= INT_MAX) {
/* We can convert this to an int (if you specifically need one): */
i = (int) j;
}
return 0;
}