help with scanf hex in C [closed]
i am trying to scan an input file with such format
r1 = 0c100009
So far I have tried this but the while loop is skipped and the output is 0.
int
read_reg (reg_t reg) {
char r, eq;
int i, hex;
while (scanf("%c,%d,%[=],%x", &r, &i, &eq, &hex)==4) {
if ((r != 'r') || (i < 1) || (i > 31) || (eq != '=')){
error();
}
reg[i] = hex;
}
printf("%#x\n",hex);
return 0;
}
Thanks for the help!
Simplify the scanf
argument:
while(scanf("r%d = %x", &i, &hex)==2)
And what do you want to happen if i
is outside limits? Should error()
be called and what then? Probably not calling reg[i] = hex;
.
Your input does not have the commas that the format string requires. You need to remove the first comma and replace the others with blanks.
Also, the %[=]
conversion specifier generates a string, not a single character; you need to define char eq[2];
and remove the ampersand when passing eq
to scanf()
.
And, when debugging such stuff, make sure you capture the return from scanf()
so you can report how badly things went wrong.
Note that you will be allowing considerable flexibility in the inputs even so:
if ((n = scanf("%c%d %[=] %x", &r, &i, eq, &hex)) == 4)
printf("Got: %c%d %s 0x%08X\n", r, i, eq, hex);
else
printf("Got: n = %d\n", n);
The format string allows all of these lines through as valid:
r1 = 0c100009
r2 = 0c100009
r3=0c100009
r 4=0c100009
In particular, disallowing 'r 4' will be difficult with the scanf()
family of functions.
Your scanf() format has all kinds of requirements that your input doesn't have... try getting rid of commas and square braces.
Regarding the braces... you seem to want to make the equals sign optional, but you cannot do that in a scanf. However, you could just scan in the entire line and then pass it through a regular expression matcher.
精彩评论