【发布时间】:2021-11-01 02:46:08
【问题描述】:
我一直在努力学习 C,并决定做一个加密项目。我想对该项目使用 ROT 13 加密,但我遇到了一个错误。该代码应该检查索引位置words[i] 处的字符的值并比较其值。如果它在 97-122 的范围内 ('a' - 'z'),请运行代码并添加加密。然而,我了解到,当我想替换像“z”这样的字母并将其移动 6 个位置时,它不起作用。将其移动 5 个位置确实有效。请看下面的代码:
#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;
}
【问题讨论】:
-
你不应该真的使用
size_t作为变量名,它是标准库中变量类型的名称 -
从这封信中减去
'a'。加13(对于rot13),如果结果>=26,再减26。再加'a'得到最终结果。
标签: c encryption ascii rot13