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.
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'
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With