0

I using a near identical copy of my code from the Caesar exercise. I am merely trying to prove the concept of shifting a single plaintext input by a single key argument. The only way to get the expected ciphertext is to fudge the key reassignment based upon Aa = 0 and Zz = 25 using k = k - 52 and k = k - 84. I know this is not correct but am unsure why the shift is behaving as it is.

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

//declare main with command line argument functionality
int main(int argc, string argv[])
{
//return error message if uncorrect # of arguments
if (argc != 2)
{
    printf("Please provide one and only one key.\n");
    return 1;
}
else
{
    //get key from command line arugment and typecast to integer
    int k = atoi(argv[1]);

    //prompt for plaintext
    printf("plaintext: ");
    string p = get_string();

    printf("ciphertext: ");

    //for each character in plaintext string
    for (int i = 0, n = strlen(p); i < n; i++)
    {
        //convert plaintext to int
        int a = p[i];
        //check if alphabetic and preserve case
        if (isalpha(a) && isupper(a))
        {
            //convert key to shift
            k = k - 52;
            //shift plaintext character by key and print
            printf("%c", ((a - 65 + k) % 26) + 65);
        }
        //check if alphabetic and preserve case
        else if (isalpha(a) && islower(a))
        {
            //convert key to shift
            k = k - 84;
            //shift plaintext character by key and print
            printf("%c", ((a - 97 + k) % 26) + 97);
        }
        //check for spaces and reprint
        else if (a == ' ')
        {
            printf(" ");
        }
    }
    printf("\n");
}
return 0;
}
1

When you are using a letter as a key and are adding it to a plaintext letter, you have to remember that both the letter and the key are letters, i.e., ASCII values. In order to make the formula work, it is necessary to convert both to numbers between 0 and 25 inclusive. The code above doesn't do the conversion on the key. It only converts the plaintext letter.

Side note: If something islower() or isupper(), it is automatically isalpha(). The isalpha() test is redundant and unnecessary.

If that 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 .