我试图从一个较大的字符串中解析出三个字符串,但只解析了前两个值。 sscanf 使用的格式字符串有问题吗?
我已经尝试过使用 "%s %[^\n\t\^]s %s\n"作为格式字符串,它适用于前两个值,但第三个值仍然为空。
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");
我希望如果我输入 say... average "cody"500,最后的 print 语句会打印出来
命令:平均引用:科迪值:500
而是打印
命令:平均引用值:科迪值:
由于某种原因,值字符串在解析时被截断。
最佳答案
如果输入字符串的形式是...
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'
也没有用。
关于c - 当一个值用双引号引起来时,如何使用 sscanf 从 C 中的字符串中解析三个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56550779/