In general, if you want to read hex, use %x
instead of %d
. But — be aware that %x
will read 10
as decimal 16, not decimal 10. You could try %i
, but that requires a 0x
or 0X
prefix to identify hexadecimal input (and would treat a leading zero as indicating octal input).
You should probably capture and test the result of fscanf()
more thoroughly. If you get EOF, so be it; but you might get 1 or 2. (In some situations, you could get 0, but with %c
as the first conversion specification, you won't get 0 for a result).
Your first call to fscanf()
should end up with printf()
printing 1 0
instead of 10
because the %c
eats the 1
leaving the 0
for the %d
.
Subsequent calls have the %c
capturing the newline \n
, and then the number.
After you read 18
, the next fscanf()
returns 1
and has the newline after the 18
in hexe
, but it fails to convert the E
into a decimal number, so 18
is left in hex1
and it is printed twice. The next call places E
into hexe
and 10
into hex1
, so you see 18E 10
in the output.
The argument is similar for why you get 12
twice. There's a newline after the 12
. Again, the %c
captures the newline and then the %d
conversion would fail (because fscanf()
encounters EOF, but it has made one successful conversion, so it doesn't report EOF yet). So hex1
still contains 12
, and 12
would therefore be printed twice.