#include #include #include static void run_strtol (const char * input) { int output; char * end; printf ("With strtol, %s", input); /* The 10 at the end means to use base 10. */ output = strtol (input, & end, 10); if (end == input) { printf (" is not a valid number.\n"); } else { printf (" -> %d\n", output); } } int main () { const char * number = "42"; /* Both strtol and atoi can cope with whitespace before the number. */ const char * whitespace_number = " 747"; const char * zero = "0"; const char * not_a_number = "cat"; /* The function atoi can convert strings into integers, but it doesn't distinguish between "zero" and failure. */ printf ("With atoi: %s -> %d %s -> %d %s -> %d %s -> %d\n", number, atoi (number), whitespace_number, atoi (whitespace_number), zero, atoi (zero), not_a_number, atoi (not_a_number)); /* Use a function to run on each of these. */ run_strtol (number); run_strtol (whitespace_number); run_strtol (zero); run_strtol (not_a_number); return 0; }