我希望能够对一行文本进行sscanf操作,并确保其中没有超出我的要求。代码如下:
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
一切都很好,但像这样的输入
INIT 9 11 3 1 1 1 9 s
也可以接受。我本以为如果添加 "\n",一切都会正常工作,因为我知道每个输入行都以 EOL 结尾,但事实并非如此。
scanf
会将换行符视为空白字符,就像制表符和空格一样。你可以读取第九个虚拟值,比如强制最大宽度为2的短字符串(%2s
),并强制转换的数量不超过8个。 - M Oehm