I'm working on a simple Ceasar Cipher encryption program in C. I am trying to make it simpler for my son and I to decipher so I put these rules: characters other than letters are unchanged while lowercase and uppercase will remain in their current case (so a Y incremented by 3 would go back to a B). The key and phrase will just be piped using a separate file (my secret!) though a sample of it's contents would be:
4
This line of text will be encrypted.
I wanted to buffer it character by character using getchar and putchar so I don't have to bother with an array whose length will always be unknown. How can I check if the character is either an upper or lower case letter and increment it by they given key, while keeping in line with the previous rules. Should putchar be inside the loop to buffer it? Here is my current code:
#include <stdio.h>
int main() {
int shift;
char msgIn, msgOut;
// space after to keep is from terminating immediately
scanf("%d ", &shift);
msgIn = getchar();
//increment current character and output until newline
while (msgIn != '\n') {
//check for upper or lower, else do nothing
if((msgIn >= 'A') && (msgIn <= 'Z')) {
msgOut = ((msgIn - 'A') + shift) % 26 + 'A'; //increment current character, not sure how to handle this better
}
//checking for lower case
else if((msgIn >= 'a') && (msgIn <= 'z')) {
msgOut = ((msgIn - 'a') + shift) % 26 + 'a'; //increment current character
}
}
putchar(msgOut); //output incremented character
}
return 0;
}
-------------- Revised code
do {
msgIn = getchar();
if((msgIn >= 'A') && (msgIn <= 'Z')) {
putchar(((msgIn - 'A') + shift) % 26 + 'A');
}
else if((msgIn >= 'a') && (msgIn <= 'z')) {
putchar(((msgIn - 'a') + shift) % 26 + 'a');
}
}
} while (msgIn != '\n')
I am thinking this code handles the input, checking, incrementing, and output better. LMK what you think.