我遇到了 sscanf 的一个奇怪问题,当我以特定顺序传递参数时,我可以正确读取所有值,并且如果我更改顺序,它可以正常工作。有人可以解释为什么会出现这种奇怪的行为吗?
非工作案例:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
int main() {
uint8_t oct1, oct2, oct3, oct4;
char buf[20];
memset(buf, 0, sizeof(buf));
sprintf(buf,"%d.%d.%d.%d", 1, 2, 3, 4);
printf("%s\n", buf);
int f = sscanf(buf,"%d.%d.%d.%d", &oct1, &oct2, &oct3, &oct4);
printf("%d.%d.%d.%d \nSuccessfully read - %d\n", oct1, oct2, oct3, oct4, f);
return 0;
}
Output:
1.2.3.4
0.0.0.4
Successfully read - 4
工作案例:
#include <stdio.h>
#include <stdint.h>
#include <string.h>
int main() {
uint8_t oct1, oct2, oct3, oct4;
char buf[20];
memset(buf, 0, sizeof(buf));
sprintf(buf,"%d.%d.%d.%d", 1, 2, 3, 4);
printf("%s\n", buf);
int f = sscanf(buf,"%d.%d.%d.%d", &oct4, &oct3, &oct2, &oct1);
printf("%d.%d.%d.%d \nSuccessfully read - %d\n", oct1, oct2, oct3, oct4, f);
return 0;
}
Output:
1.2.3.4
4.3.2.1
Successfully read - 4
最佳答案
uint8_t
的正确格式说明符是SCNu8
来自 <inttypes.h>
的宏.用法应该是:
sscanf(buf,"%" SCNu8 ".%" SCNu8 ".%" SCNu8 ".%" SCNu8, &oct1, &oct2,
&oct3, &oct4);
同样,SCNu32
和 SCNu16
对于 uint32_t
和 uint16_t
分别和SCNd8
, SCNd16
, SCNd32
对于 int8_t
, int16_t
和 int32_t
分别。
请注意,这些固定整数类型(在 C99 中引入)是可选类型。
旁白:
sprint
很危险,因为它们无法防止缓冲区溢出。建议使用snprintf()
相反:
snprintf(buf,sizeof buf, "%d.%d.%d.%d", 1, 2, 3, 4);
此外,memset()
荷兰国际集团buf
这是不必要的,因为您将立即写入它(请注意 snprintf()
总是 NUL 终止缓冲区)。
关于c - 可变顺序对 sscanf 重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34378854/