Search code examples
cvariablesascii

how do i get a variables ASCII value and use it in a sum


for(i=0;i < strlen();i++;)
{
postnum = argv[i] - k
}

i'm trying to write a Caesars encryption program for a course i'm taking, and pretty much i want to have the ASCII value of the i'th character in the string to have a key(k) added to the ASCII value to encrypt the string. i know to get a chars ASCII number you do 'a' or what ever letter you need but how do i get it from a char variable?


Solution

  • Just treat each character as an int and add k to the char:

     int i, k = 1;
     char *str = "abc";
     char *ctext = malloc(sizeof(char) * (strlen(str) + 1));
     for (i = 0; i < strlen(str); i++) {
          ctext[i] = str[i] + k;
     }
     ctext[i] = '\0';
    
     printf("%s\n", ctext);
    

    will output:

    bcd