basics · intermediate · ~15 min
Validate input while scanning.
Check that every % in a format string introduces a recognised conversion.
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.
A NUL-terminated format string fmt.
Returns 1 if every % is followed by an allowed character, otherwise 0.
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 %)
% with no following character is invalid.% is valid.% are exactly: d s c x %.A NUL-terminated format string fmt.
1 if every % is followed by an allowed char, otherwise 0.
Allowed chars after %: d s c x %. A dangling % is invalid.
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.