Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char and Int printing two different values

Tags:

c

char

printf

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.

like image 692
A. Shin Avatar asked Aug 17 '20 15:08

A. Shin


2 Answers

Your file doesn't contain the integers 3 2 1 2 2 2 3.

  • It contains a stream of bits
  • Groups of 8 bits can be grouped together. These groupings are called bytes
  • These bytes are interpreted by a character encoding (most likely ASCII or UTF-8), to represent the characters 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'.

like image 123
Alexander Avatar answered Nov 14 '22 08:11

Alexander


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:

ASCII-Table

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
like image 1
RobertS supports Monica Cellio Avatar answered Nov 14 '22 08:11

RobertS supports Monica Cellio