Search code examples
cencryptioncaesar-cipher

C language: there is a trailing character after the last character of my output


I am making a Caesar's Cipher for my lab sheet, and have made it able to encrypt 3 subtitution(Caesar's Cipher), which is the point of the exercise. But there has been one thing bugging me. First, there is a trailing character if i put it other than 3. For example, by typing "malware", and 2 for key. This is my code :

#include<stdio.h>
#include<stdlib.h>

int main()
{
   char text[100];
   int key,i;

   printf("Please enter a word/sentence (lowercaps) for encrypting :\n ");
   fgets(text,100,stdin);
   printf("Please enter the key that you desire : eg:14\n");
   scanf("%d", &key);
   for(i=0;i<strlen(text);i++)
   {
      if (key>=26)
      {
         key=key%26;
      }
      if (text[i]==' ')
      {
         continue;
      }
      if(text[i]+key>'z')
      {
         text[i]-=97;
         text[i]+=26;
         text[i]+=key;
         text[i]%=26;
         text[i]+=97;
      }
      else
      {
         text[i]=text[i]+key;
      }
   }

   printf("this is your encrypted text : %s", text );
}

I hope I followed the correct indentation methods for coding. Got a lot of dislikes because of that


Solution

  • Code is 1) not properly detecting when a char is a lower case letter 2) encrypting non-letters including '\n' from fgets() which is causing OP's "trailing character after the last character of my output".

    Instead:

    if (text[i] >= 'a' && text[i]<= 'z') {
       text[i] = (text[i] - 'a' + key)%26 + `a`;
    }
    else {
      ; // nothing 
    }
    

    Alternatively

    if (islower((unsigned char) text[i]) {
       text[i] = (text[i] - 'a' + key)%26 + `a`;
    }
    

    Note: the above depends on char are encoded as ASCII.

    A solution that does not depend on ASCII.

    static const char lowercase[] = "abcdefghijklmnopqrstuvwxyz";
    char *p = strchr(lowercase, text[i]);
    if (p) {
      int offset = (p - lowercase + key)%26;
      text[i] = lowercase[offset];
    }