当我尝试解密消息时,输出不是应该的输出。我抬头看了Caesar Cipher,并理解了这个概念,但是从我的角度看,一切似乎都是正确的。可能是我正在使用switch语句吗?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void){
char phrase[100], option, ph;
int key;
printf("Would you like to encrypt (e) or decrypt (d)? \n");
scanf(" %c", &option);
printf("Enter a message (100 characters or less): \n");
scanf(" %s", phrase);
printf("Enter key: \n");
scanf(" %i", &key);
switch(option){
case 'e':
{
for(int i = 0; phrase[i] != '\0'; i++){
ph = phrase[i];
if(ph >= 'a' && ph <= 'z'){
ph = ph + key;
if(ph > 'z'){
ph = ph - 'z' + 'a' - 1;
} //end of if
phrase[i] = ph;
} // end of if
else if(ph >= 'A' && ph <= 'Z'){
ph = ph + key;
if(ph > 'Z'){
ph = ph - 'Z' + 'A' - 1;
}
phrase[i] = ph;
} // end of else if
} // end of for
printf("Encrypted message: %s\n", phrase);
break;
} // end of case 'e'
case 'd':
{
for(int i = 0; phrase[i] != '\0'; i++){
//~ phrase[i] = phrase[i] + 3;
ph = phrase[i];
if(ph >= 'a' && ph <= 'z'){
ph = ph + key;
if(ph > 'z'){
ph = ph - 'z' + 'a' + 1;
}
phrase[i] = ph;
} // end of if
else if(ph >= 'A' && ph <= 'Z'){
ph = ph + key;
if(ph > 'Z'){
ph = ph - 'Z' + 'A' + 1;
} // end of if
phrase[i] = ph;
} // end of else if
} // end of for
printf("Decrypted message: %s\n", phrase);
break;
} // end of case 'd'
} // end of switch
} // end of function
用于加密的GCC输出:
您要加密(e)还是解密(d)? e
输入消息(不超过100个字符): 你好
输入键: 3
加密的消息:khoor
用于解密的GCC输出:
您要加密(e)还是解密(d)? d
输入消息(不超过100个字符):
输入键: 3
解密后的邮件:nkrru
答案 0 :(得分:0)
您的加密逻辑和解密逻辑是相同的,即,对于解密,您应该在减去时添加密钥。您还需要更改溢出检查,使其低于'a'
:
case 'd':
{
for(int i = 0; phrase[i] != '\0'; i++){
//~ phrase[i] = phrase[i] + 3;
ph = phrase[i];
if(ph >= 'a' && ph <= 'z'){
ph = ph - key; // subtract
if(ph < 'a'){ // switch wraparound check
ph = ph + 'z' - 'a' - 1;
}
phrase[i] = ph;
} // end of if
else if(ph >= 'A' && ph <= 'Z'){
ph = ph - key; // subtract
if(ph < 'a'){ // switch wraparound check
ph = ph + 'Z' - 'A' - 1;
} // end of if
phrase[i] = ph;
} // end of else if
} // end of for
printf("Decrypted message: %s\n", phrase);
break;
} // end of case 'd'