Search code examples
cencryptioncs50caesar-cipher

Caesar Cipher is not working with spaces


I'm having a hard time getting spaces to display properly. The following is an output of what is printed:

./CaeserC 13[A
Encrypt message by 13[A spaces
Please insert your message:
Hello World 
Your message is: Hello World
Your encrypted message is:Uryybadbeyq

It needs to be Uryyb Jbeyq

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

int main (int argc, string argv[])
{
    string kinp = argv[1];
    int k = atoi(argv[1]);
    printf("Encrypt message by %s spaces\n", kinp);
    printf("Please insert your message:\n");
    string p = GetString();
    int lettern;
    printf("Your message is: %s\n", p);
    printf("Your encrypted message is:");
    for (int i=0, n=strlen(p); i<n; i++)
        {  
            lettern=p[i];
            //printf("%i \n", lettern);
        }
    if (lettern==32)
    {
        printf("%c", ' ');
    }
    if (lettern>= 65 && lettern<=90)
    {
    for (int i=0, n=strlen(p); i<n; i++)
        {  
            printf("%c", ((p[i]+k-65)%26)+65);
        }
    }
    if (lettern>= 97 && lettern<=122)
    {
        for (int i=0, n=strlen(p); i<n; i++)
        {
            printf("%c", ((p[i]+k-97)%26)+97);
        }
    }

    printf("\n");
}

Solution

  • printf("Your encrypted message is:");
    for (int i=0; p[i]; i++){
        if(isupper(p[i]))
            putchar((p[i]+k-'A')%26 +'A');
        else if(islower(p[i]))
            putchar((p[i]+k-'a')%26 +'a');
        else
            putchar(p[i]);
    }