I would like to sscanf a line and make sure that that there is nothing more then what I wanted in it. The code looks like this:
void parse_init_command(char *buffer, command *new_command) {
if (sscanf(buffer,
"%s %d %d %d %d %d %d %d\n",
new_command->name,
&new_command->data[0],
&new_command->data[1],
&new_command->data[2],
&new_command->data[3],
&new_command->data[4],
&new_command->data[5],
&new_command->data[6]) != 8) {
strncpy(new_command->name, "WRONG_INPUT", 15);
}
}
When I get an input like:
INIT 9 11 3 1 1 1 9
everything is fine, but then an input like this
INIT 9 11 3 1 1 1 9 s
is also accepted. I thought that if I added "\n" everything would work fine, since I know that every input line ends with an EOL, but it didn't.
scanf
treats the new-line character as white space, just like tabs and spaces. You could read a ninth dummy value, a short string with enforced max. width (%2s
) perhaps, and enforce that the number of conversions doesn't exceed 8. – Pacheco