A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
atof converts a string to double. atoi converts to int. atol converts to long. They skip leading whitespace, parse an optional sign and digits, and stop at the first non-numeric character. They return 0 on failure. They do not report errors. They do not set errno. They do not tell you where parsing stopped. If the input is "abc", they return 0. If the input is "0", they also return 0. You cannot distinguish success from failure. For production code, use strtod, strtol, and strtoul instead.
#include <stdio.h>#include <stdlib.h>int main(void) {printf("atoi(\"42\"): %d\n", atoi("42"));printf("atoi(\" -7\"): %d\n", atoi(" -7"));printf("atoi(\"12abc\"): %d\n", atoi("12abc"));printf("atoi(\"abc\"): %d\n", atoi("abc"));printf("atoi(\"0\"): %d\n", atoi("0"));printf("\natof(\"3.14\"): %.4f\n", atof("3.14"));printf("atof(\"2.5e2\"): %.4f\n", atof("2.5e2"));printf("atof(\"xyz\"): %.4f\n", atof("xyz"));printf("\natol(\"100000\"): %ld\n", atol("100000"));return 0;}
atoi("12abc") returns 12. It parsed the leading digits and stopped. atoi("abc") returns 0. atoi("0") returns 0. The last two are indistinguishable. If your program branches on whether the user entered a valid number, atoi cannot tell you. strtol can. The endptr reveals whether any digits were consumed.
Quick prototypes. Competitive programming. Internal tools where the input format is guaranteed. Situations where 0 is an acceptable default for malformed input. In these contexts, atoi is shorter and the lack of error checking does not matter. In production code that handles external input, use strtol with endptr checking. The extra three lines of code prevent an entire class of silent-failure bugs.
The ato family is convenient and unsafe. Know when each is appropriate. Default to the strto family for anything that touches external input. Next: atexit, for registering cleanup functions that run when the program terminates normally.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.