I have been trying to learn C and decided to do an encryption project. I want to use ROT 13 encryption for the project but I have been getting an error. The code is supposed to check the value of a char at index position words[i]
and compare its value. If it's in the range of 97-122 ('a'
- 'z'
), run the code and add the encryption. I learned, however, that when I want to replace a letter like 'z' and move it 6 positions, it doesn't work. Moving it 5 positions does work. Please see the code below:
#include <stdio.h>
#include <string.h>
int main(){
char words[25]= "ABC MNO XYZ";
printf("%s \n", words);
printf("size of 'words' is %d \n", strlen(words));
int size_t = strlen(words);
for (int i=0; i < size_t; i++){
printf("%c \n", words[i]);
}
printf("unencrypted ends here... \n\nStarts the cipher\n");
//converts array to lowercase for ascii purposes
for (int i=0; i < size_t; i++){
words[i]= tolower(words[i]);
}
for (int i=0; i < size_t; i++)
{
char res = 'z';
if(words[i]>=97 && words[i]<=122)
{
words[i] = words[i]+6;
while(words[i] > 122)
{
res = words[i]-res;
printf("The value of res is: %d\n", res);
words[i]=96;
words[i]= words[i]+res;
}
}
//'res' ascii value equals 122
//if words[i] is more than 122 (z), subtract 122 from it and store it in res
//restart words[i] at position before 'a', then add res
//not sure why but after 122 + 6 or more positions, does not reset to a char before 'a'
//gives those weird chars at 128+ ascii locations
printf("%c \n", words[i]);
}
return 0;
}