c - Reading multiple values from formatted string using sscanf -
i'm trying extract 2 values string. first 8 digit hexadecimal value, , second unsigned 1-4 digit value. values should preceded command tells program values, in case "read". examples of format:
"read 0x1234abcd 2000" "read 0x00000001 10"
i want both extract 2 values , confirm format, , have following lines of code:
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... }
the hex-value read correctly, second value not , n 1. doing wrong?
what doing wrong?
input: "read 0x1234abcd 2000" format: "read 0x%x[0-9a-fa-f]{8} %u[0-9]{1,4}"
input "read 0x"
matches format "read 0x"
. far.
input "1234abcd"
matches format "%x"
. far. +1 return value.
input " "
not match format "["
. scanning stops. sscanf()
returns 1.
alternatives, read 2nd value decimal value.
const char *f1 = "read 0x%x %u"; const char *f2 = "read 0x%x%u"; // space not need, yet looks const char *f3 = "read %x%u"; // read addr hex, 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 above
the above code not fail
"read 0x0x123 +1234" "read 0x123 456 xyz" "read 0x123 12345" "read 0x+123 -123"
should op want more error checking. 8 limits text input addr
8 non-white-space characters. sentinel
detects tailing non-white-space garbage.
unsigned addr; unsigned len; char sentinel; int n = sscanf(str, "read 0x%8x %4u %c", &addr, &len, &sentinel); if (n != 2){ // wrong format... }
the above fail
"read 0x123 456 xyz"
what closest op original code obliges more work. use "%[...]"
test allowable scan set.
#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); ... }
i see no line of input code not fail/pass op might desire, except allow x
or x
.
Comments
Post a Comment