-5

This code is supposed to encipher text based off the command argument input key and print out the enciphered text. However it doesn't print spaces and punctuation. Can someone explain what is wrong?

Example use:

$ ./caesar 12
world, say hello!
iadxp, emk tqxxa!
$

Code:

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

int main(int argc, string argv[])
{
    if (argc>2 || argc<2)
    {
        printf("Please enter a valid argument.\n");
        return 1;
    }  

    string input = GetString();

    int key = atoi(argv[1]);

    for(int i = 0, l = strlen(input); i < l; i++)
    {
        //if(isalpha(input[i]))
        //{
            char c = input[i];
            int letternum = c;

            if(isupper(c))
            {
                int upper = 'A';
                int alphanum = letternum - upper;

                int newint = (alphanum + key) % 26;

                newint = newint + upper;

                char newchar = newint;

                printf("%c", newchar);
            }

            if(islower(c))
            {
                int lower = 'a';
                int alphanum = letternum - lower;

                int newint = (alphanum + key) % 26;

                newint = newint + lower;

                char newchar = newint;

                printf("%c", newchar);
            }
        //}

    }    

    printf("\n");
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

1

Add else after if() blocks.

Change from

       if(isupper(c)) {
         ...
       }
       if(islower(c)) {
         ...
       }

to

       if(isupper(c)) {
         ...
       } else if(islower(c)) {
         ...
       } else {
         putc(c);
       }

Note: pedantic code would use the following as is...() functions are defined for all int values in the range of unsigned char and EOF.

isupper((unsigned char) c)
islower((unsigned char) c)

Note2: Code will have problems if alphanum + key < 0. May want to add a test to insure key is not too negative or use the following to insure key >= 0.

int key = atoi(argv[1]) % 26 + 26;

Note3: OP's code assumes A-Z and a-z are consecutive like in ASCII encoding (which is certainly the case 99.99+% of the time.) but not in EBCDIC

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256