c - 加密过程工作一半

标签 c caesar-cipher

#include <stdio.h>
#include <string.h>
int main()
{
char inpusr[100];
int i, length,key;
length=100;
scanf("%[^\n]s",inpusr);
scanf("%d",&key);
printf("%s\n", inpusr);
    for(i = 0; i <=length; i++) {
        if(inpusr[i] >= 97 && inpusr[i] <=122) {
            inpusr[i] = inpusr[i] + key;
            if (inpusr[i]>122){
             inpusr[i] = (inpusr[i] - 122)+96;

            }
        }

    }
printf("%s\n", inpusr);
return 0;
}

我用 C 编写了一个程序,用凯撒密码方法加密字符串,但为什么当输入为“z”且 key 大于 6 时,我的代码无法显示移位后的字母。

最佳答案

首先,请遵循一些有关如何操作 char 数组的指南。 字符数组不是字符串。

char inpusr[100];
scanf("%[^\n]s",inpusr);

如果您在这里输入“Hello”,您知道数组中会得到什么吗? [H e l l o\0\0\0\0\0 %^j .....] 下次你可以使用

#include <string.h>
memset( inpusr , 0 , sizeof(inpusr));

现在关于你所说的代码

if(a>10 && a<100)
{
    if (a<5) // This is a logic error.If a<10 you don't get in to block.
    {
    }
}

出于兴趣,凯撒密码方法是 A=(x+n) 模 26。

这是一个工作代码:

#include <stdio.h>
#include <string.h>

int main()
{
char inpusr[100];
int i, length,key;
length=100;
memset( inpusr , 0 , sizeof(inpusr));
scanf("%[^\n]s",inpusr);
scanf("%d",&key);
printf("%s\n", inpusr);
for(i = 0; i <=length; i++)
{
    if(inpusr[i] >= 97 && inpusr[i] <=122)
    {
        inpusr[i] = (((inpusr[i] - 97 + key) % 26) + 97);
    }
    else if ((inpusr[i] >= 65 && inpusr[i] <=90))
    {
        inpusr[i] = (((inpusr[i] - 65 + key) % 26) + 65);
    }

}
printf("%s\n", inpusr);
return 0;
}

关于c - 加密过程工作一半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48438949/

相关文章:

CS50 Caesar - ASCII 字母和输出格式

python - 统计一个 list

c - 前后增量运算符关联性问题 :(

c - C 中的逆波兰表示法

c - caesar.c 的奇怪输出

凯撒密码和反向文本程序

java - AES 128 解密中的预期 IV 长度 0 错误

c - 按升序对键盘输入的整数进行排序和打印,而不使用 C 中的数组

c fwrite() 写入数据只对结构变量之一?

c - pthread_cond_broadcast 在 POSIX 中没有忙等待