Rage91
Rage91

Reputation: 87

Ceasar Cipher in C

I wrote this code in c to make use of caesar cipher algorithm however if i enter longer sentences it gives weird symbols at end for example I got this in the output window :

Enter the text : THIS PROGRAM IS AN EXAMPLE OF CAESAR CIPHER

Enter the table : ABCDEFGHIJKLMNOPQRSTUVWXYZ

Enter the key : 3

WKLVBSURJUDPBLVBDQBH DPSOHBRIBFDHVDUBFLSKHUCä

Do you want to decrypt it back? Enter 1 if you want to : 1

THIS PROGRAM IS AN EXAMPLE OF CAESAR CIPHER.▬

Press any key to continue . . .

would appreciate any help

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;

}

Upvotes: 0

Views: 346

Answers (1)

Adrian Krupa
Adrian Krupa

Reputation: 1937

You put semicolon at the end of line so your loop do nothing

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

You got wrong if in text is symbol missing in table, for example space or '\n'-new line sign.

Upvotes: 1

Related Questions