我正在尝试从较大的字符串中解析三个字符串,但是仅解析了前两个值。 sscanf使用的格式字符串有问题吗?
我已经尝试使用“%s%[^ \ n \ t \ ^] s%s \ n”作为格式字符串,它适用于前两个值,但第三个值保留为空白。 / p>
printf(">> ");
fflush(stdout);
fgets(input, MAX_STR, stdin);
sscanf(input, "%s %[^\t\n]s\n", command, value);
/* parse it differently if the command is average*/
if(!strcmp(command, "average")) {
/* clear the values */
strcpy(command, "");
strcpy(reference, "");
strcpy(value, "");
/* re-parse the input */
sscanf(input, "%s \"%[^\t\n\"]s\" %[^\t\n]s\n", command, reference, value);
}
printf("command: %s reference: %s value: %s\n");
我希望,如果我输入……平均“ cody” 500,那么最后的打印语句将打印出来
命令:平均参考值:科迪值:500
但它打印
命令:平均参考值:科迪值:
由于某些原因,解析时值字符串被切断。
答案 0 :(得分:2)
如果输入字符串的格式为...
command "reference" value
...,其中command
和value
没有空格,代码可以使用:
char command[100], reference[100], value[100];
int n = 0;
sscanf(input, "%99s \"%99[^\"]\" %99s %n", command, reference, value, &n);
if (n > 0 && input[n] == 0) {
// success
printf("command: '%s' reference: '%s' value: '%s'\n", command, reference, value);
}
成功扫描将设置n
的值,而input[n]
将是空字符。
通过分解格式来进行解析通常更容易
#define FMT_CMD "%99s"
#define FMT_REF " \"%99[^\"]\""
#define FMT_VAL "%99s"
sscanf(input, FMT_CMD FMT_REF FMT_VAL " %n",
command, reference, value, &n);
对于sscanf(input, "%s %[^\t\n]s\n", command, value);
,command, value
没有宽度限制,存在缓冲区溢出的风险。格式中的最后's'
无用。格式的结尾'\n'
也没有用。