java string sscanf_是否有一个版本的sscanf()不是从第一个字节开始的?

使用 "%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 的返回值 .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值