-1

密码适用于 islower 部分,但不适用于 isupper 部分。例如,如果我给一个密钥 3 并输入I like pie!!要加密,我得到O olnh slh!!我也试过HELLO并得到了NKRRU. isupper 部分也返回标点符号而不仅仅是字母。我还没有弄清楚为什么要更改原始消息以匹配密码消息。

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

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;            
}
4

2 回答 2

3

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);or

cipher = malloc(length + 1);
if (cipher === NULL) Handle_OutOfMemeory();
cipher[length] = '\0';
for ( int i = 0; i < length; i++) 
  ...
于 2014-02-09T19:24:27.443 回答
2

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

还有两分感谢 Chux 发现了多余的分号。

于 2014-02-09T19:24:52.553 回答