使用23作为密钥将“barfoo”加密为“yxocll”
输出无效的ASCII文本
日志
正在运行/凯撒23。。。
正在检查输出“密文:yxocll”。。。
有人看到我的代码有什么问题吗?它似乎对大写字母很有效,但对于小写字母和某些“键”,我得到了错误的结果,并且无法找出原因。任何帮助都将不胜感激。
例子:
如果我试图用17的密钥加密“foo”,它应该返回“wff”,但我的代码只返回“w”。用我写的代码,它是说去位置128,这不是一个字母,但我的代码是说,如果超过122,扣除26。等于并返回“102”,即“f”。这与删除被分配到127有关吗
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
if (argc == 2) {
int a = atoi (argv[1]);
int b = a%26;
printf("plaintext: ");
//get string
string s = get_string();
printf ("ciphertext: ");
//iterate through string
for (int i=0, n =strlen(s); i<n; i++) {
//check if character is a letter
if ( isalpha (s[i])) {
//check if letter is uppercase
if (isupper (s[i])) {
//calculate position of character in ASCI by adding 'Key'. If character is over 90, decrease character location by 26
char c = (s[i] + b);
if (c > 90) {
char d = c - 26;
printf ("%c", d);
} else
printf("%c", c);
} else
//For lowercase letters. If character location is over position 122, decrease location by 26
{
char e = (s[i] + b);
if (e>122) {
char f = e - 26;
printf("%c", f);
} else
printf("%c", e);
}
} else //print non letters with no change made
{
printf ("%c", s[i]);
}
}
}
printf ("\n");
return 0;