我有一个字符串结构,例如“[first something]=[second something”]
我认为 sscanf 将是一种分离它们的方法!
但是,scan 永远不会使用 %n 正确报告偏移量。
这行代码很像:
char data[100];
char source[] = "username=katy"
int offset=-1;
sscanf([source],"%[^=],%s%n",data,&offset)
printf("sscanf is reporting %s with an offset of %i\n"
)
但输出总是看起来像:
sscanf is reporting username with an offset of -1
有人可以帮我解决这个问题吗?
(是的,我知道这让我们很容易出现缓冲区溢出错误 - 这在代码的早期已经被禁止...)
最佳答案
scanf
格式字符串中的逗号没有意义。代替 "%[^=],%s%n"
,尝试 "%[^=]=%s%n"
。您还应该对两个字符串设置字段宽度限制,否则您可能会溢出目标缓冲区,并且您传递给 sscanf
的参数太少(只有一个字符串,而不是另一个) .
代码的更正版本可能如下所示:
char key[100], data[100];
char source[] = "username=katy"
int offset=-1;
sscanf(source,"%99[^=]=%99s%n",key,data,&offset)
printf("sscanf is reporting %s with an offset of %i\n", data, offset);
关于c - 获取 sscanf 读取了多少个字符? (%n),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17076270/