让Caesar Cipher绕过去

让Caesar Cipher绕过去,c,cs50,caesar-cipher,C,Cs50,Caesar Cipher,我可以让它打印纯文本并按键值移位,但是 我有点困惑于如何将字母包装起来,以及如何将其实现到我的代码中 如有任何建议,将不胜感激 多谢各位 #include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> //Gets number of user arguments and the key. int mai

我可以让它打印纯文本并按键值移位,但是 我有点困惑于如何将字母包装起来,以及如何将其实现到我的代码中

如有任何建议,将不胜感激

多谢各位

#include <cs50.h>
#include <stdio.h>
#include <string.h> 
#include <ctype.h> 
#include <stdlib.h>

//Gets number of user arguments and the key.
int main (int argc,  string argv[]) { 
    if(argc != 2) {
        printf("try again\n");
    }
    //Converts string to int. 
    int key = atoi(argv[1]);

    //Will store the chars + key. 
    int result;

    printf("Please enter what you would like to encrypt: "); 

    //Gets plaintext from user. 
    string plainText = get_string();       

    //Iterates over the user's input, checking for the case of each char. 
    for (int i = 0; i <= strlen(plainText); i++) {
        if (toupper(plainText[i]) || tolower(plainText[i])) { 
                    result = plainText[i]; 
        }
    //Checks if i'th char is a letter and shifts it. 
        if (isalpha(plainText[i])) { 
                    result = plainText[i + key]; 
        } 
    } 
    printf("%c", result);  
}
#包括
#包括
#包括
#包括
#包括
//获取用户参数和键的数目。
intmain(intargc,字符串argv[]){
如果(argc!=2){
printf(“重试\n”);
}
//将字符串转换为int。
int key=atoi(argv[1]);
//将存储chars+密钥。
int结果;
printf(“请输入您想要加密的内容:”;
//从用户获取纯文本。
字符串纯文本=获取字符串();
//迭代用户的输入,检查每个字符的大小写。

对于(int i=0;i来说,最简单的方法之一是使用模
%
运算符

现在谈谈你的代码

for (int i = 0; i <= strlen(plainText); i++) {
if (toupper(plainText[i]) || tolower(plainText[i])) { 
            result = plainText[i]; 
}
//Checks if i'th char is a letter and shifts it. 
if (isalpha(plainText[i])) { 
            result = plainText[i + key]; 
  } 
} 
printf("%c", result);  
上述逻辑的解释::首先检查字母是小写还是大写,以便将其设置在
0
26
的范围内, 然后用键的模加上键,这样它就可以返回到0,然后再通过加上“a”的值将其转换为ascii

e、 g.如果
明文[i]=“x”(ascii值120)
键=5
,则

plainText[i] =  120
plaintext[i] - 'a' = 23
(plaintext[i] - 'a') + key = 28 // Out of 0-25 alphabet range
((plaintext[i] - 'a') + key) % 26 = 2 // Looped back
(((plaintext[i] - 'a') + key) % 26) + 'a' = 99 (ascii value for 'c')
如您所见,在将
5
添加到
x
之后,我们得到了
c

最后,打印的位置应该在循环内,否则它只打印最后的输入,这是不正确的

我希望我所做的一切都能帮助你,记住CS50的荣誉准则。我还建议你在他们的论坛上问这些问题,因为他们是一个更容易使用的社区


另外,享受CS50,它是让你开始学习的最好的CS课程之一;)

可能重复这应该做什么:
if(toupper(明文[i])| tolower(明文[i])
?非常感谢你的帮助。最好使用字符常量而不是整数常量:
result=((明文[i]-'A')+键)%26+'A';
。这让意思更清楚了。@David,谢谢你的建议,我已经更新了答案。只是关于可移植性的一点意见:该标准没有为执行字符集指定ASCII编码,事实上也有其他编码(例如,某些IBM系统上使用了EBCDIC)。此解决方案可能会起作用,但在考虑可移植性的情况下,可能需要另一种方法。OP的代码还有一些其他问题。
exit()
语句需要在开始时伴随错误消息。
result
需要在每个循环迭代开始时分配当前字符。打印编码字符的
printf()
语句需要在循环内部移动。
plainText[i] =  120
plaintext[i] - 'a' = 23
(plaintext[i] - 'a') + key = 28 // Out of 0-25 alphabet range
((plaintext[i] - 'a') + key) % 26 = 2 // Looped back
(((plaintext[i] - 'a') + key) % 26) + 'a' = 99 (ascii value for 'c')