c - C语言中简单的凯撒密码,无需用户输入

标签 c encryption codeblocks caesar-cipher

我需要编写一个程序,将特定消息(S M Z V Q O P I V)存储在一组char变量中,然后在将解密后的消息一次输出一个字符之前,应用移位值为8。通过使用包含多个%c说明符的格式字符串,输出应看起来像一个字符串。

我只能找到需要用户输入的代码示例,尽管我刚刚对其进行了修改,使其具有已经具有所需值的变量,但我仍在努力理解代码应如何遍历字符串的意义-即ch = ch-'Z'+'A'= 1,这对于在字母之间使用运算符实际上意味着什么?

到目前为止,这就是我所拥有的,尽管代码输出[Ub ^ YWXQ ^作为加密的消息-有什么办法可以纠正应该为字母的字符? Z应该变成H吗?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char message[] = "SMZVQOPIV";
    int i;
    int key = 8;

    printf("%s", message);

    char ch= message [i];

    for(i = 0; message[i] !='\0';++i)
    {
        ch = message[i];

        if(ch >= 'A' && ch <= 'Z'){
            ch = ch + key;
            if (ch > 'z'){
                ch = ch - 'Z' + 'A' - 1;
            }
            message[i] = ch;
        }
    }

    printf("Encrypted Message: %s", message);
    return 0;
}


有人可以简短地向我介绍代码的外观和原因吗?自从我进行任何编程以来已经有一段时间了,并且我主要使用Python,所以在C语言中有些失落。

最佳答案

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char message[] = "SMZVQOPIV";
    int i;
    int key = 8;

    printf("%s\n", message);
    /*
    *   "printf("%s", message);" -> "printf("%s\n", message);"
    *   you have to print a newline('\n') by yourself,
    *   it's not automatic as "print" in python
    */


    /*
    *   There was a "char ch= message [i];" 
    *   unecessary and it gives error(i is not initialised)
    */

    for (i = 0; message[i] != '\0'; ++i)
    {

        char ch = message[i];
        /*
        *   "ch = message[i];" -> "char ch = message[i];"
        *   when you define an object in C, you have to specify its type
        */

        if (ch >= 'A' && ch <= 'Z') {
            ch = ch + key;
            if (ch > 'Z') {
                /*
                *   Main error here, but just a blunder
                *   "if (ch > 'z') {" -> "if (ch > 'Z') {"
                *   Upper case is important ;), 'Z' is 90 in decimal,
                *   'z' is 122
                */

                ch = ch - 'Z' + 'A' - 1;
            }
            message[i] = ch;
        }
    }

    printf("Encrypted Message: %s", message);
    return 0;
}

关于c - C语言中简单的凯撒密码,无需用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58902698/

相关文章:

encryption - 使用弱密码,bcrypt或SHA-256 + AES-256加密文件?

C++ 半透明窗口 SDL

c - 为什么我在重新分配时不必从堆中释放内存?

c - 以下代码输出整数、 float 、字符变量

java - 使用套接字传输加密文件并使用 DES 和 MD5 解密文件

c++ - 无法在 C++ 代码块中构建和运行

c++ - 需要在 Codeblocks 中启用 C++11

c - 从 .map 文件获取数据

我可以使用 C-preprocssor 将整数转换为字符串吗?

php - 如何加密表单数据?