ling wrote:
Hi,
I'm trying to do fscanf from a file with integers.
I've tried using both %d and %i hoping that I would figure out their difference.
When I checked the man pages, the only difference I could tell was
d: Matches an optionally signed decimal integer ...
i: Matches an optionally signed integer ...
What's the difference between an integer and a decimal integer?
Notice below that 0423 is an integer, but is interpreted differently with
%d (decimal value 423) and %i (octal 0423 = decimal 275) and 0x46 is 0 with
%d (the scan stops at the non-digit 'x') but hex 46 = decimal 70 with %i.
If you want decimal values with possibly leading zeroes, you must use %d
since %i will interpret it as octal.
#include <stdio.h>
int main(void)
{
char input[] = "375 0423 0x46";
int a, b, c;
unsigned ua, ub, uc;
printf("The input string is \"%s\"\n\n", input);
printf("attempting to read as integer\n");
a = b = c = 0;
sscanf(input, "%i %i %i", &a, &b, &c);
printf("decimal values: %d %d %d\n\n", a, b, c);
printf("attempting to read as decimal integer\n");
a = b = c = 0;
sscanf(input, "%d %d %d", &a, &b, &c);
printf("decimal values: %d %d %d\n\n", a, b, c);
printf("attempting to read as octal integer\n");
ua = ub = uc = 0;
sscanf(input, "%o %o %o", &ua, &ub, &uc);
printf("unsigned decimal values: %u %u %u\n\n", ua, ub, uc);
printf("attempting to read as hex integer\n");
ua = ub = uc = 0;
sscanf(input, "%x %x %x", &ua, &ub, &uc);
printf("unsigned decimal values: %u %u %u\n\n", ua, ub, uc);
return 0;
}
The input string is "375 0423 0x46"
attempting to read as integer
decimal values: 375 275 70
attempting to read as decimal integer
decimal values: 375 423 0
attempting to read as octal integer
unsigned decimal values: 253 275 0
attempting to read as hex integer
unsigned decimal values: 885 1059 70
--
Martin Ambuhl