C语言-凯撒加密程序

标签 c encryption caesar-cipher

我想制作一个程序,它接受字母并使用凯撒加密将它们从向上 1 值转移到 b。它必须使用字符串才能执行此操作。

我的问题是我的程序不会将用户的输入放入字符串中。 (我试图将 Guy[10] 放入 scanf 中,但这只会导致程序崩溃——所以我愿意将不正确的 Guy 放在那里,以便程序可以编译)。

#include <stdio.h>


int main(){
int i=0; //setting the individual slot number for the array-- later used in the while loop
char guy[10];
printf("Enter Plain Text:");
scanf("%s",&guy); //takes user's input-- such as "abc" and puts it into its respective slot in the array guy[10] r-right?

while (guy[10] != '\0'){ //while loop that runs until it reaches the end of the string
    if ((guy[i]) >= 'A' && (guy[i]<= 'Z')){ //moves capital letter values up 1
        guy[i]=guy[i]++; //makes the current "slot" number go up 1 value. Example: a = 97 + 1 -> b = 98
        }
    if ((guy[i]) >= 'a' && (guy[i]) <= 'z'){// moves lower case letter values up 1
        guy[i]=guy[i]++;
    }
    i++; //moves the array's interval up to the next "slot"

}
printf("Encrypted text is: %s",guy);
}

最佳答案

您的第一个问题是这一行:

scanf("%s",&guy);

as guy 是一个数组,因此我们不需要获取指向它的指针,它的名称在此上下文中被视为指针。只需执行以下操作:

(void) scanf("%s", guy);

您的第二个问题是这一行:

while (guy[10] != '\0')

正如 WhozCraig 在他的评论中指出的那样 - 这应该使用索引 i,而不是 10

第三个问题是这种说法没有什么意义:

guy[i]=guy[i]++;

合理的替代方案包括:

guy[i] = guy[i] + 1;
guy[i]++;
guy[i] += 1;

第四个问题是你没有处理过环绕。例如。 'Z' 在你的代码中映射到什么?看起来它会显示为“[”而不是“A”。

第五个问题是 scanf() 可能会溢出数组 guy,因为它的输入大小是无限的。对于 guy[10],我们需要执行以下操作:

scanf("%9s", guy);

将输入限制为九个字符,并为最后的“\0”留出空间。在这种情况下,使用 fgets() 会是更好的选择,因为它更安全,而且我们不需要 scanf() 的解析能力:

fgets(guy, 10, stdin);

以下是解决这五个问题的返工:

#include <stdio.h>

int main() {
    char text[10];

    printf("Enter Plain Text: ");
    (void) fgets(text, 10, stdin); // takes user's input -- such as "abc" and put it into its respective slots in the array

    int i = 0; // slot index for the array

    while (text[i] != '\0') { // loop until reach end of string

        if (text[i] >= 'A' && text[i] <= 'Z') { // move capital letter values up 1
            // make the letter go up 1 modulo 26. Example: A = 65 + 1 -> B = 66; Z = 90 + 1 -> A = 65
            text[i] = ((text[i] - 'A' + 1) % ('Z' - 'A' + 1)) + 'A';
        } else if (text[i] >= 'a' && text[i] <= 'z') { // move lower case letter values up 1
            text[i] = ((text[i] - 'a' + 1) % ('z' - 'a' + 1)) + 'a';
        }

        i++; // move the array's index up to the next "slot"
    }

    printf("Encrypted text is: %s\n", text);
}

关于C语言-凯撒加密程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40856352/

相关文章:

有人可以向我解释为什么这是可能的吗?

c - 需要 C 语言帮助的 RSA 加密代码

java - "DataBase encryption in Hibernate"返回 'encryptedBody' 中的未知列 'field list'

用于加密/解密段落的凯撒密码程序

C - 将枚举用于位标志 - 警告 : enumerated type mixed with another type

c - C语言中switch case可以接受多少个参数?

c - 各种编译器编译的链接库

c# - 重定向后验证用户

ruby - 在此凯撒密码中, "print i[-1]"是如何从 z 换行到 a 的?

C中的凯撒密码加密程序