Reputation: 51
My code is reading a file containing integers: 3 2 1 2 2 2 3
FILE *fptr;
fptr = fopen(argv[1], "r");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
int c = fgetc(fptr);
printf("%c", c);
fclose(fptr);
This is outputting the first number 3 as expected but when using it as an integer
printf("%d", c);
it outputs 51 instead? I'm trying to use these numbers as inputs for a counter and positions in a 2D array.
Upvotes: 5
Views: 641
Reputation: 15032
Characters are stored as integer according to an encoding scheme. Your system seems to use the ASCII encoding set. Every single character has a respective ASCII code integer value, which determines how that character is stored in memory.
'1'
has the ASCII value 49
, '2'
the ASCII value 50
and '3'
has the ASCII value 51
.
Here is a list of the standard ASCII set:
When you use printf("%c", c);
, c
is read as a character. As c
holds the character '3'
, it prints the character value 3
.
When you use printf("%d", c);
instead, c
is read as an integer and what is printed is not 3
, it is its relative ASCII code value, which is 51
.
I'm trying to use these numbers as inputs for a counter and positions in a 2D array.
If you want to convert this character value to an integer, you can use c - '0'
and assign it to another variable:
int c = fgetc(fptr);
int i_c = c - '0';
printf("%d", i_c);
OR back to c
again:
int c = fgetc(fptr);
c = c - '0';
printf("%d", c);
Output in both cases:
3
Upvotes: 1
Reputation: 63197
Your file doesn't contain the integers 3 2 1 2 2 2 3
.
3 2 1 2 2 2 3
.A character encoding is a mapping between byte patterns and the characters they're associated with. For example, the UTF-8 states that 11111111 000000000 10011111 10011000 10000011
maps to the character Unicode character 1F603, "SMILING FACE WITH OPEN MOUTH": 😃.
What you just saw is that the first byte of your file is 00110011
, which is the ASCI encoding for the character '3'
.
Upvotes: 3
Reputation: 134316
You're reading 3
as a character, .
In The system, following ASCII encoding, decimal value of '3'
is 51
, so when you print the read value, it prints 51
If you want the literal value, you can use something like
printf("%d", c- '0');
as the numbers 0
to 9
are bound to have strictly increasing serial values in encoding.
Upvotes: 0