basics · intermediate · ~15 min

Parse an integer

Turn text into a number — what scanf does under the hood.

Challenge

Turn a string into an integer with strict validation — what scanf("%d") does under the hood.

Task

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.

Input

A NUL-terminated string s, and a pointer out for the parsed value on success.

Output

Returns 1 on success (with *out set); 0 on any invalid input.

Example

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)

Edge cases

  • Empty input and trailing non-digit characters both return 0.
  • A lone - with no digits returns 0.

Rules

  • Reject any trailing junk — strict parsing, unlike atoi.

Input format

A NUL-terminated string s, and an int *out for the result.

Output format

1 on success (with *out set); 0 on invalid input.

Constraints

Optional leading '-' then digits only; reject empty input and trailing junk.

Starter code

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.