Number/String Conversions in C
Converting between text and numbers is daily C work with a safety gradient: atoi/atof are convenient but blind (no error reporting — "abc" silently becomes 0), strtol/strtod report fully via end-pointers and errno (the robust choice), and sscanf parses formatted input with checkable returns. The other direction is sprintf/snprintf into buffers.
Rule: quick scripts may atoi; real programs strtol with endptr validation (did it consume input? all of it?) plus errno checks for overflow. Unvalidated numeric parsing is how configs and protocols turn typos into catastrophes.
atoi is blind
atoi("abc") returns 0 exactly like atoi("0") — success and failure are indistinguishable. Convenient, untrustworthy.
strtol reports
char *end; long v = strtol(s, &end, 10); then end == s means nothing parsed, *end != 0 means trailing junk, errno == ERANGE means overflow.
sscanf parses patterns
sscanf(buf, "%d:%d", &h, &m) with == 2 checked parses structured text with per-field validation.
snprintf stringifies
Numbers to text go through bounded snprintf — formatted, terminated, overflow-proof.
#include <stdio.h>#include <stdlib.h> int main(void) { char *good = "42"; char *bad = "abc"; printf("%d %d\n", atoi(good), atoi(bad)); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.