使用 "%n 是处理扫描前一部分扫描完成的字符串的常用方法,因为 "%n" 记录扫描到该点的偏移量 .
将其附加到格式的末尾并测试索引值是否从-1更改 . 这适用于简单和复杂的格式 .
int scanf_buffer_2_step(const char * buffer) {
int i;
double d;
// Initialize to a value that a successful scan would never use.
int n = -1;
// append vv vv
sscanf(buffer, "Index:%d,%n", &i, &n);
// Test for success
if (n < 0) return 1; // fail
// Advance pointer to next string position
buffer += n;
// Do it some more
n = -1;
sscanf(buffer, " Data:%lf End of the line %n", &d, &n);
if (n < 0) return 1; // fail
buffer += n; // Advance pointer to next string position
if (buffer[0] != '\0') return 1; // fail (extra data)
printf("(%i %f)", i, d);
return 0;
}
int main(void) {
printf("%d\n", scanf_buffer_2_step("Index:1, Data:123.456 End of the line"));
printf("%d\n", scanf_buffer_2_step("Index:1, Data:123.456 End of the line extra"));
printf("%d\n", scanf_buffer_2_step("Index:1,"));
return 0;
}
产量
(1 123.456000)0
1
1
对于最终扫描,如果在字符串末尾允许使用 '\n' ,则考虑添加 " %n" .
对于 fscanf() ,还会出现问题,例如检查 EOF 的返回值 .