凯撒密码无法正确计算C代码

时间:2018-12-14 05:10:13

标签: cs50 caesar-cipher

我需要有关密码的帮助。我一切正常,直到遇到'a'后需要回到'z'的程序。我不确定该如何处理,因此任何输入都将有所帮助。为了清楚起见,我迷失的部分是if ('c' > z)所在的地方。

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

// using argc and argv to get a shift number from the command line then 
// running a check to see the value of it
int main(int argc, string argv[])
{
char c;
int key = 0;

if (argc == 2)
{
    key = atoi(argv[1]);
}
else if (argc == 1)
{
    printf("ERROR\n");
    return 1;
}

string message = get_string("Enter a message to encrypt: ");
//getting the message you want to change
int len = strlen(message);

//loop to see when the array ends and run through it to
//shift each letter
for (int i = 0; message[i] != '\0'; i++)
{
    c = message[i];
//shifting the letters
    if (c >= 'a' && c <= 'z')
    {
        c = c + key;
//this is what doesn't work, when it hits z it doesn't go 
//back up and i'm not sure how to make it start at 'a' 
//again and then continue counting.
        if(c > 'z')
        {
            continue;
        }

        message[i] = c;
    }
//same as above with same error
    else if (c >= 'A' && c <= 'Z')
    {
        c = c + key;

        if (c > 'Z')
        {
            continue;
        }

        message[i] = c;
    }
}

printf("ciphertext: %s\n", message);
}

1 个答案:

答案 0 :(得分:0)

如果您希望将'z' + 1之类的值变为a,将'z' + 2之类的值变为b,依此类推,则可以更改此值:

    if(c > 'z')
    {
        continue;
    }

类似于:

    if(c > 'z')
    {
        c = c - 'z' + 'a' - 1;
    }

顺便说一句:您的代码无法处理溢出,因此不适用于任何key值。较小的键值会很好,但是某些较高的键值会引起问题。考虑以下代码:

#include <stdio.h>

int main(void) {
    char c = 'z';
    int key = 6;
    c = c + key;
    if ('c' > 'z')
    {
        printf("Greater than z\n");
    }
    else
    {
        printf("Less than z or equal to z\n");
    }

    int x  = c;
    printf("%d\n", x);
    return 0;
}

在某些平台(例如https://ideone.com/2LOvCU)上,这可能会提供输出

Less than z or equal to z
-128

我想这不是你想要的。也许您应该将所有计算都保留为(无符号)整数类型。