MsA
MsA

Reputation: 2979

Why I am getting negative integer equivalent of character

I am accepting space separated digits of number. Then I am iterating over individual characters to get their integer equivalents as shown in below code:

#include <stdio.h>
#include <string.h>

int main()
{
    setbuf(stdout, NULL);

    int numLength;
    printf("Enter number length: ");
    scanf("%d",&numLength);

    getchar();
    char str[2*numLength];
    printf("Enter number: ");
    fgets(str, 2*numLength, stdin);

    for(int i=0;i<2*numLength;i=i+2)
    {
        printf("%d ",('0'-*(str+i)));
    }

    return 0;
}

Below is sample output:

Enter number length: 5
Enter number: 2 k 6 a 0
-2 -59 -6 -49 0 

My doubt is why it is giving negative of integer equivalents?

(You can run the code online here)

Upvotes: 0

Views: 52

Answers (1)

sepp2k
sepp2k

Reputation: 370112

'0' - '2' is -2 for the same reason that 0 - 2 is also -2: '2' is greater than '0' by 2, so the result of subtracting the greater from the lesser number is -2.

You want *(str+i) - '0' (or str[i] -'0') if you want the result to be positive.

Upvotes: 3

Related Questions