basics · intermediate · ~15 min
Turn text into a number — what scanf does under the hood.
Turn a string into an integer with strict validation — what scanf("%d") does under the hood.
Implement int parse_int(const char *s, int *out) that parses s as a signed decimal integer: an optional leading -, then one or more decimal digits, and nothing else. On success, store the value in *out and return 1. Return 0 if s is empty, has no digits, or contains any non-digit character. No main — the grader calls it.
A NUL-terminated string s, and a pointer out for the parsed value on success.
Returns 1 on success (with *out set); 0 on any invalid input.
parse_int("123", &v) -> 1, v == 123
parse_int("-45", &v) -> 1, v == -45
parse_int("12a", &v) -> 0 (trailing 'a')
parse_int("", &v) -> 0 (no digits)
- with no digits returns 0.atoi.A NUL-terminated string s, and an int *out for the result.
1 on success (with *out set); 0 on invalid input.
Optional leading '-' then digits only; reject empty input and trailing junk.
int parse_int(const char *s, int *out) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.