basics · intermediate · ~15 min
Iterate argv the way a CLI parser does.
Count the command-line flags in an argv array, the way a CLI parser starts out.
Implement int count_flags(int argc, char **argv) that returns how many arguments start with a '-'. Skip argv[0] (the program name) and scan argv[1] through argv[argc-1]. No main — the grader calls it.
The argument count int argc and the argument vector char **argv (with argv[0] being the program name).
Returns the number of arguments (after argv[0]) whose first character is '-'.
{"prog","-a","foo","-b"} -> 2
{"prog"} -> 0
{"prog","-x","-y","-z"} -> 3
argc == 1), the count is 0.argv[0] is the program name, not an argument.int argc and char **argv (argv[0] is the program name).
The number of arguments after argv[0] that start with '-'.
Skip argv[0]; scan indices 1..argc-1.
int count_flags(int argc, char **argv) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.