gpt4 book ai didi

c - 使用 sscanf 从格式化字符串中读取多个值

转载 作者:行者123 更新时间:2023-12-02 09:17:15 25 4
gpt4 key购买 nike

我正在尝试从字符串中提取两个值。第一个是 8 位十六进制值,第二个是无符号 1-4 位值。这些值之前还应该有一个命令,告诉程序如何处理这些值,在本例中为“读取”。一些格式示例:

"read 0x1234ABCD 2000"
"read 0x00000001 10"

我想提取两个值并确认格式,并具有以下代码行:

uint addr;
uint len;

int n = sscanf(str, "read 0x%x[0-9a-fA-F]{8} %u[0-9]{1,4}", &addr, &len);

if (n != 2){
// Wrong format...
}

十六进制值读取正确,但第二个值读取不正确,并且 n 始终为 1。我做错了什么?

最佳答案

What am I doing wrong?

Input:  "read 0x1234ABCD 2000"
Format: "read 0x%x[0-9a-fA-F]{8} %u[0-9]{1,4}"

输入“read 0x”与格式“read 0x”匹配。到目前为止还不错。

输入“1234ABCD”与格式“%x”匹配。目前很好。返回值+1。

输入""与格式"["不匹配。扫描停止。 sscanf() 返回 1。


替代方案,将第二个值读取为十进制值。

const char *f1 = "read 0x%x %u";
const char *f2 = "read 0x%x%u"; // Space not need, yet looks good
const char *f3 = "read %x%u"; // Always read addr as hex, even with/without 0x
const char *f4 = "read %x %u";
const char *f5 = "read%x%u";

unsigned addr;
unsigned len;
int n = sscanf(str, fn, &addr, &len); // select format from above

上面的代码不会失败

"read 0x0x123 +1234"
"read 0x123 456 xyz"
"read 0x123 12345"
"read 0x+123 -123"

OP 应该需要更多的错误检查吗? 8 将 addr 的文本输入限制为 8 个非空白字符。 sentinel 检测尾部非空白垃圾。

unsigned addr;
unsigned len;
char sentinel;
int n = sscanf(str, "read 0x%8x %4u %c", &addr, &len, &sentinel);
if (n != 2){
// Wrong format...
}

上面确实失败了

"read 0x123 456 xyz"

最接近OP原始代码的东西需要更多的工作。使用“%[...]”测试允许的扫描集

#define F_RD    "read"
#define F_SP "%*[ ]"
#define F_ADDR "0x%8[0-9a-fA-F]"
#define F_LEN "%4[0-9]"
#define F_SEN " %c"
char addr_s[8+1];
char len_s[4+1];
char sentinel;
int n = sscanf(str, F_RD F_SP F_ADDR F_SP F_LEN F_SEN, addr_s, len_s, &sentinel);
if (n == 2){
// Success
unsigned long addr = strtoul(addr_s, (char **)NULL, 16);
unsigned len = strtoul(len_s, (char **)NULL, 10);
...
}

除了我允许 xX 之外,我看不到该代码不会按照 OP 的要求失败/通过的任何输入行。

关于c - 使用 sscanf 从格式化字符串中读取多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45755269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com