I'm trying to create a simple Caesar shift program in C but I can't seem to figure it out. The program keeps crashing. Any help would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int arc, const char* argv[])
{
int shift = atoi(argv[1]);
char message[256];
strcpy(message, argv[2]);
int i;
for(i = 0; i < strlen(message); i++) {
printf("%c", message[i] + shift);
}
putchar('\n');
return 0;
}
You're not correctly implementing the Caesar Cipher. Your code includes the following line, which is wrong:
printf("%c", message[i] + shift);
To do this correctly, you'll want to convert that to a function:
printf("%c", encrypt(message[i], shift));
And let's implement the function:
char encrypt(char input, int shift) {
if (input >= 'a' && input <= 'z')
return ((input - 'a' + shift) % 26) + 'a';
if (input >= 'A' && input <= 'Z')
return ((input - 'A' + shift) % 26) + 'A';
return input;
}
And just to explain what the math is doing in that function:
input - 'a' tells us what position in the alphabet the input is (assuming input is a lowercase letter). So if the input is 'c', then we will get a 2 back. If the input is 'z', we get 25.input - 'a' + shift gets us the new position of the character that we are using to do the cipher. Note that this could be a larger number than the alphabet (26 characters).[0 - 25].Note that this only works because the character codes for a to z and A to Z are consecutive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With