C 中的凯撒密码 : can't seem to wrap around the latter letters of the alphabet

标签 c math encryption caesar-cipher

#include <stdio.h>

int main()
{
    char text[1000], alpha;
    int n;

    printf("Please type in text:\n");
    scanf("%[^\n]s", text);

    printf("\nRotation number:  "); // rotates letters to the right.
    scanf("%d",&n);
    printf("\n");

    n = n % 26; // to wrap around alphabet.

    int i = 0;
    while (text[i] != '\0')
    {
        if((text[i] >= 'a' && text[i] <= 'z'))
        {
            alpha = text[i];

            text[i] += n;

这是我不明白为什么它不起作用的部分:

            if(text[i] > 'z')

            {
                text[i] = 'a' + (n - (26 % (alpha - 'a')));
            }

它一直工作到字母“d”为止。 'f' 只给出 '\200'。

关于为什么我的代码不起作用的任何想法?

        }
        i++;
    }

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

    return 0;
}

最佳答案

这部分你不明白为什么不起作用:

if(text[i] > 'z')
{
    text[i] = 'a' + (n - (26 % (alpha - 'a')));
}

可以用

简单地解决
if(text[i] > 'z')
{
    text[i] -= 26;
}

UPDATE 你正在使用 char which 可能已签名,因此将密码,比如 20 添加到 z 将产生一个数字> 128,即负数。

我建议修改

int alpha;   // changed from char

//...

alpha = text[i] + n;
if (alpha > 'z')
    alpha -= 26;
text[i] = alpha;

关于C 中的凯撒密码 : can't seem to wrap around the latter letters of the alphabet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32159063/

相关文章:

仅在调试时正确输出

伪代码中的加密算法

javascript - 使用 background-size :contain 时获取 div 背景图像的 XY 坐标和高度/宽度

c# - 加密值每次都不会返回相同的值

encryption - "Could not perform unpadding: invalid pad byte.."的解密错误

c - 使用 sprintf() 获得正确的格式

c - 逐行读取字符串数组中的内容

c - C : A variable changes when it shouldn't 中的 SDL 1.2

java - 带有数学运算符的字符串到整数

c++ - 如何命令坐标对?