0

This code is encrypting till the key is 25, from 26 to above it is not giving output for lower case.In upper case with the key of 2 its output of "AAA" is "CACACA" rather than "CCC". It is not giving any output for "numeric" and all special characters as they should be output as it is.Need help to solve this.

#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main (int argc,string argv[])

{
    if (argc!=2)//if argc is not equel to 2.
    {
       printf("please enter 2 command line arguments\n");
        return 1;
    }


  int key=atoi(argv[1]);//changing char at argv[1] to int.

  string txt = GetString();

  int len=strlen(txt);

  for (int i=0;i<len;i++)

  {
     if (isalpha(txt[i]))//if alphabet.
      {
          if (isupper(txt[i]))//if is upper case
          {int alpha=txt[i]+key;//add int key to int value of char.
           if (alpha<=90)
           {
               printf("%c",alpha);
           }
           else {
           printf("%c",alpha%26);//for z to a roll over.

           }

          }
          if (islower(txt[i]))//if lower case
          {int alphaa=txt[i]+key;//add int key to int value of txt[i].
          if (alphaa<=122)
         { 
             printf("%c",alphaa);

          }
          else {
              printf("%c",alphaa%26);//for a to z roll oover
          }
      }
    else
    {
        printf("%c",txt[i]);//print same without changing it.
    }
  }}
  printf("\n");
  return 0;
}
0

You can't apply the modulo % technique to the ASCII values of a letter. It will only result in a non-printable or graphic character. The letter has to be converted to a number from 0 to 25 inclusive, the key added, modulo applied, and then convert the result back to ASCII.

If you don't understand how to do that, you should review the class material and videos that cover it.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .