C中的凯撒密码

时间:2014-03-15 11:44:53

标签: c

我在c中编写了这段代码以使用凯撒密码算法但是如果我输入更长的句子,它会在结尾处给出奇怪的符号,例如我在输出窗口中得到了这个:

输入文字:本程序是CAESAR CIPHER的例子

输入表格:ABCDEFGHIJKLMNOPQRSTUVWXYZ

输入密钥:3

WKLVBSURJUDPBLVBDQBH DPSOHBRIBFDHVDUBFLSKHUCä

你想要解密吗?如果您想要输入1:1

这个程序是CAESAR CIPHER的例子。

按任意键继续。 。

非常感谢任何帮助

void encrypt (char table[],char entext[],char text[],int key)
{
     int i,j;
     int k = strlen(table);
     for (i=0;i<strlen(text);++i)
     {
         if (text[i]!='\0')
         {
             for (j=0; text[i] != table[j] ;j++);
                 entext[i] = table[(j+key)%k];
         }
     }
     entext[i+1] = '\0';
     puts(entext);
}

void decrypt (char table[],char detext[],char text[],int key)
{
     int i,j;
     int k = strlen(table);
     for (i=0;i<strlen(text);++i)
     {
         if (text[i]!='\0')
         {

             for (j=0; text[i] != table[j] ;j++);
             {
                 int temp = j - key;
                 if (temp < 0)
                 {
                    j = k + temp;
                    detext[i] = table[j];
                 }

                 else
                     detext[i] = table[j-key];
             }
         }
     }
     detext[i+1] = '\0';
     puts(detext);
}


int main()
{
    char table[100],text[100],entext[100],detext[100];
    int i,j,key,choice;
    printf("Enter the text : ");
    gets(text);
    printf("Enter the table : ");
    gets(table);
    printf("Enter the key : ");
    scanf("%d",&key);
    encrypt(table,entext,text,key);
    printf("Do you want to decrypt it back? Enter 1 if you want to : ");
    scanf("%d",&choice);
    if (choice == 1)
    {
       decrypt(table,detext,entext,key);
    }
    system("pause");
    return 0;

}

1 个答案:

答案 0 :(得分:1)

你在行尾添加分号,这样你的循环就什么都不做了

for (j=0; text[i] != table[j] ;j++);

如果texttable中的符号缺失,例如空格或'\n' - 换行符号,那就错了。

相关问题