#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/