0

In my c program I have attempted to make arguments passed by the command line to be converted into numbers. In other words I want 'a' to be equal to 1 and 'z' to be equal to 26.

#include <stdio.h> 

int main(int argc, char *argv[])
{
    int i,j,num;
    for(i=1; i<argc; ++i)
    {
        for(j=0; argv[i][j] != '\0'; ++j)
        {
            //printf(":%c", argv[i][j]);

            if (argv[i][j] >= 'A' && argv[i][j] <= 'Z')
            {
                num = argv[i][j] - 'A';
            }
            else if (argv[i][j] >= 'a' && argv[i][j] <= 'z')
            {
                num = argv[i][j] - 'a';
            }
            num = num + '0';
            printf("%d\n", num);
        }
    }
    printf("\n");
    return 0;
}

The problem is when I run this command:

./encript a

I would expect my program to return a value of one but instead I get this:

48
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256

1 Answers1

1

In your program, you do this addition:

num = num + '0';
printf("%d\n", num);

This will add 48 (ascii of 0) to the calculated number.

In addition, 'A'-'A' equals 0 and not to 1

eyalm
  • 3,366
  • 19
  • 21