Alaska
Alaska

Reputation: 11

Caesar Cipher Going back to 'A'/'a'

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


void encrypt(char *theString, int shift) {
    while (*theString) {
        if (isalpha(*theString)) {
            *theString += shift;
        }
        theString++;
    }
}

int main(void) {
    int shift;
    int *ip;

    ip = &shift;
    char theString[80];
    printf("Enter String: ");
    fgets(theString, 80, stdin);
    printf("Enter Number: ");
    scanf("%d", &shift);

    encrypt(theString,shift);
    puts(theString);

    return(0);
}

Got this far, thanks for the help.

Now, I need help going back to 'A' when the user types 'Z', instead of going to [ (and for lowercase letters). I know I need some if statements, not sure which ones. Thanks for any and all help.

Upvotes: 1

Views: 180

Answers (1)

Edwin Buck
Edwin Buck

Reputation: 70909

First rotate the character. This might lead to invalid characters (rotating past Z).

After rotating the character, check the character to see if it is greater than 'Z'. If it is, then you need to figure out how far past 'Z' it is. To do this, subtract 'Z' from the character.

You now have "how far past Z" the character is. You need to take this number and convert it to "how far past A", which means you would subtract 1.

Now that you have "how far past A", you can just add the character 'A' to the value, and you will get the desired value.

To summarize, "subtract off 'Z', add 'A' and subtract 1".

while (*theString) {
    if (isalpha(*theString) && isLower(*theString)) {
        *theString += shift;
        while (*theString > 'z') {
            *theString = *theString - 'z' - 1 + 'a';
        }
    } else if (isalpha(*theString) && isUpper(*theString)) {
        *theString += shift;
        while (*theString > 'Z') {
            *theString = *theString - 'Z' - 1 + 'A';
        }
    }
    theString++;
}

Upvotes: 1

Related Questions