Hi. I am trying to make a caesar cypher.
For those that don't know what it is:
It takes a string and an integer and moves each letter in the string along by that integer. So say the string was ABCD and the shift was 1, then the new message would be BCDE. Ya dig?
Anyway, Ive almost got it complete, but there are a few bugs which I can't seem to track down:
Caesar.c:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char shift(char *str, char c, int shiftnum, int length);
int main(void) {
char stringtoshift[100];
char shiftvalue[10];
char *s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int len = strlen(s); /* = 62 */
printf("Enter string: ");
fgets(stringtoshift, 100, stdin);
int length = strlen(stringtoshift);
printf("Now enter the shift value: ");
fgets(shiftvalue,10,stdin);
int sh = atoi(shiftvalue)% len;
if(sh<0)
sh += strlen(s); /* if shift is -1 for eg, its the same as shift being 61 */
int j;
for(j=0;j<length;j++) {
if(stringtoshift[j] == ' '); /*skip spaces*/
else
stringtoshift[j] = shift(s,stringtoshift[j],sh,len);
printf("%c", stringtoshift[j]);
}
stringtoshift[j]='\0';
printf("\n");
return 0;
}
char shift(char *str, char c, int shiftnum, int length) {
int i;
for(i=0; *str!=c; str++)
i++; /* i is the position we are currently in the string str */
if(i+shiftnum >= length) {
/* if you are on Y (position 51) for example
and shift is 23, then it will spill over
(a-z = 26, A-Z = 26, 0-9 = 10, total = 62)
(62-51=11, 23-11=12) so we have to move 12
places from 'a' */
shiftnum += i - length; /* 23 - (62-51) = 23 + 51 - 62 */
for(;*str!='a';str--); /* reset (go back to beginning of s) */
}
for(;--shiftnum>=0;) /*same is for(k=0;k<shiftnum;k++) */
str++;
return *str;
}
Running:
Code:
$gcc -o caesar caesar.c
$./caesar
Enter string: HELLO THERE
Now enter the shift value: -1
GDKKN SGDQD�
$ ./caesar
Enter string: hello
Now enter the shift value: -8
96ddgo
These are just a few examples of unexpected output. If you could, try playing about with it yourself to see what is wrong, I would be very grateful. Thanks