C中的凯撒密码适用于较低的上部

密码适用于较低部分但不适用于上部分。 例如,如果我给一个3键,然后输入I like pie!! 要加密,我得到O olnh slh!! 我也尝试了HELLO并获得了NKRRU 。 isupper部分也返回标点而不仅仅是字母。 我还没弄清楚为什么原始消息被改变以匹配密码消息。

 #include  #include  #include  #include  #include  int main (int argc, string argv[]) { /* Get key from user at command line Get plaintext from user Use key to encipher text: c[i] = (p[i] + k)%26 Print ciphered message */ string message, cipher; int key; // command line, if user doesn't enter 2 arguments return 1 and request a valid //encryption key and rerun. if (argc != 2) { printf("Please enter a valid encryption key and rerun program.\n"); return 1; } else { key = atoi(argv[1]); } printf("Enter the message you wish to encrypt.\n"); message = GetString(); cipher = message; int length = strlen(message); for ( int i = 0; i < length; i++) { if (isalpha(message[i])) { if (isupper(message[i])) { cipher[i] = (message[i] - 'A' + key) % 26 + 'A'; } else (islower(message[i])); { cipher[i] = (message[i] - 'a' + key) % 26 + 'a'; } } else continue; //message[i] contains punctuation or a space } printf("Your original message was..\n"); printf("%s\n", message); printf("The encrypted message is...\n"); printf("%s\n", cipher); return 0; } 

if按@interjay,错字和丢失。

更改

 else (islower(message[i])); 

 // v else if (islower(message[i])) // or simply else // Since `message[]` is an alpha, but not upper 

有了错误,当文本为大写时, cipher[i] = (message[i] - 'A' ...cipher[i] = (message[i] - 'a' ...发生。给定cipher = message ,密码被应用了两次。


@keshlam关于丢失缓冲区的观点是一个重要问题。 但我想知道什么是string 。 这是某种C ++ lite字符串吗? 如果它是char * ,代码可以使用cipher = strdup(message); 要么

 cipher = malloc(length + 1); if (cipher === NULL) Handle_OutOfMemeory(); cipher[length] = '\0'; for ( int i = 0; i < length; i++) ... 

你正在覆盖消息,因为你说cipher = message; 这意味着现在都指向同一块内存。 分配新的输出缓冲区。

还有两点向Chux发现了多余的分号。