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


int main(int argc, string argv[])
{
    // validate the command line argument's parameters
    int key = atoi (argv[1]);
    if (argc != 2 || key < 0)
{
    printf("Please use a single positive interger\n");
    return 1;
}

// get users plaintext
char* plaintext;
printf("Plaintext: ");
plaintext = get_string();


// iterate over characters in plaintext and shift plaintext character by key
printf("ciphertext: ");
int int_A = (int) 'A';
int int_a = (int) 'a';
for (int j = 0, n = strlen(plaintext); j < n; j++)
{
    int pt = (int) plaintext[j];
    if (isalpha(plaintext[j]))
    {
        if (isupper(plaintext[j]))
        {
            printf("%c", ((pt - int_A) + key) % 26);
        }
        if (islower(plaintext[j]))
        {
            printf("%c", ((pt - int_a) + key) % 26);
        }
    }
    else
    {
        printf("%c", plaintext[j]);
    }

}
printf("\n");
return 0;
}

So the code runs just fine and prints out the non-alpha characters but I just can't figure out how to print out the ciphered characters. I've tried rewriting the loop for iterating through plaintext with different methods on printing out the text but I just don't see it... YET! So please guide me in the right direction :)

I think the problem (obviously?) lies in my print statement; it used to be a mixture of char* and int but I changed them all into int for easier read of the debug50 tool.

1 Answer 1

1

Please do not use atoi(argv[1]) before testing argc. If there's no argument, atoi might segfault.

You shift character to 0..25, add the key, wrap around back into 0..25 using remainder operator, but then you forget to shift back into character range.

Just like you subtracted 'A', add it after everything else is done, that is after applying the % 26.

Also, you might need to adjust the spelling in your "plaintext" and "ciphertext" strings. Not sure how check50 sees it, but case might be significant, unless the current tests are a bit more relaxed.

1
  • Aaah, damn it.. I guess I should've rubber duckied a bit more... Thank you kind sir!
    – Librarian
    Nov 14, 2017 at 17:53

You must log in to answer this question.

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