gpt4 book ai didi

c - 为什么使用凯撒密码加密时无法打印空格?

转载 作者:行者123 更新时间:2023-11-30 19:26:15 25 4
gpt4 key购买 nike

我正在尝试编写一个使用凯撒密码方法加密或解密消息的 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

最佳答案

你的做法基本上是正确的,但不是正确的做法。您正在使用两个循环来检查字母是否在上面给定的数组中。您可以像这样轻松检查:

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 提到的,您需要在 cases 之间进行 break。此外,正如他再次所说,if (count = 1) 并不检查 count 的值:它只是对其进行赋值。如果您需要比较,请使用 == (尽管您无论如何都不需要它)。

关于c - 为什么使用凯撒密码加密时无法打印空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57744107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com