basics · intermediate · ~15 min

Validate a format string

Validate input while scanning.

Challenge

Check that every % in a format string introduces a recognised conversion.

Task

Implement int is_valid_format(const char *fmt) that returns 1 if fmt is well-formed and 0 otherwise. The string is valid when every % is immediately followed by one of the characters d, s, c, x, or %. A % at the very end of the string (followed by nothing) is invalid. A string with no % at all is valid. No main — the grader calls it.

Input

A NUL-terminated format string fmt.

Output

Returns 1 if every % is followed by an allowed character, otherwise 0.

Example

is_valid_format("%d-%s-%x %%")   ->   1
is_valid_format("no specs")      ->   1
is_valid_format("%q")            ->   0     ('q' is not allowed)
is_valid_format("ends with %")   ->   0     (dangling %)

Edge cases

  • A trailing % with no following character is invalid.
  • A string containing no % is valid.

Rules

  • Allowed characters after % are exactly: d s c x %.

Input format

A NUL-terminated format string fmt.

Output format

1 if every % is followed by an allowed char, otherwise 0.

Constraints

Allowed chars after %: d s c x %. A dangling % is invalid.

Starter code

int is_valid_format(const char *fmt) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.