我正在尝试编写一个使用Caesar密码方法加密或解密消息的C程序。用户可以使用空格输入消息,但是我的C程序会打印其他字符(例如[],字母符号或有时是字母)。谁能建议我更改代码以打印空格?
#include <stdio.h>
#include <conio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
void main()
{
int i,j,s,k,p,choice,key,n,count;
char alpha[27]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char msg[100],encrypt[100];
printf("\t\t\tCEASER CIPHER");
printf("\n\t\t\t-------------");
printf("\n1.Encrypt");
printf("\n2.Decrypt");
printf("\nEnter the choice:");
scanf("%d",&choice);
switch(choice){
case 1 :{system("cls");
printf("Enter the message to be encrypted:");
fflush(stdin);
gets(msg);
printf("\nEnter the shift key:");
scanf("%d",&key);
n=strlen(msg);
printf("\nThe encrypted key is :");
for(i=0;i<n;i++){
count=0;
for(j=0;j<27;j++){
if(msg[i]==alpha[j]){
s=j+key;
k=s%26;
encrypt[i]=alpha[k];
count=1;
break;
}
}
if(count=1)
printf("%c",encrypt[i]);
else if(count=0)
printf("-");
}
}
case 2 :{
}
}
}
1.output:-
Enter the message to be encrypted:hello world
Enter the shift key:3
Th encrypted key is:khoor'zruog
expected output:-
Enter the message to be encrypted:hello world
Enter the shift key:3
Th encrypted key is:khoor-zruog
1.output:-
Enter the message to be encrypted:how are you
Enter the shift key:3
Th encrypted key is:krz-duhabrx
expected output:-
Enter the message to be encrypted:how are you
Enter the shift key:3
Th encrypted key is:krz-duh-brx
答案 0 :(得分:0)
您所做的基本上是正确的,但不是正确的方法。您正在使用两个循环来检查字母是否在上面的数组中。您可以像这样轻松检查:
if (msg[i] >= 'a' && msg[i] <= 'z') // if msg[i] is letter
因此,这样编写代码会更容易:
for (int i = 0; i < n; ++i)
{
if (msg[i] >= 'a' && msg[i] <= 'z')
{
encrypt[i] = msg[i] + key;
if (encrypt[i] > 'z')
encrypt[i] = 'a' + (encrypt[i] - 'z'); // or encrypt[i] -= 26;
}
}
而且,正如约翰森(Johathan)所述,您需要在break
之间使用cases
。而且,正如他再次说的那样,if (count = 1)
并不检查count
的值:它只是分配它。如果需要比较,请使用==
(尽管无论如何都不需要)。