Learn C
#include "arraysstrings/string_conversions.h"

Number/String Conversions in C

#concept

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.

#how it works
1

atoi is blind

atoi("abc") returns 0 exactly like atoi("0") — success and failure are indistinguishable. Convenient, untrustworthy.

2

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.

3

sscanf parses patterns

sscanf(buf, "%d:%d", &h, &m) with == 2 checked parses structured text with per-field validation.

4

snprintf stringifies

Numbers to text go through bounded snprintf — formatted, terminated, overflow-proof.

#example
#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;
}
Output
42 0
1atoi("42") parses genuinely to 42.
2atoi("abc") also returns 0 — indistinguishable from a real zero, demonstrating the blindness.
3Both print side by side: convenient output, zero diagnostics — the lesson's whole point.
#use cases
Parsing CLI numbers and config values with validated strtol
Reading structured records with sscanf return-count checks
Formatting numbers into bounded buffers with snprintf
Replacing every atoi in reviewed code with checked conversion

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.