0

My code is for pset2 caesar is:

##include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int k;

int main(int argc, string argv[])
{
if (argc != 2)
{
    printf("Usage: ./caesar key\n");
    return 1;
}
k = atoi(argv[1]);
if (k <= 0)
{
    printf("Usage: ./caesar key\n");
    return 1;
}
else
{
    string text = get_string("plaintext: ");
    printf("ciphertext: ");
    for (int i = 0, n = strlen(argv[i]); i < n; i++)
    {
        if (islower(text[i]))
        {
            printf("%c", (((text[i] + k) - 97) % 26) + 97);
        }
        else if (isupper(text[i]))
        {
            printf("%c", (((text[i] + k) - 65) % 26) + 65);
        }
        else
        {
            printf("%c", text[i]);
        }
    }
    printf("\n");
    return 0;
}
}

However, when I try to encrypt "world, say hello!" as "iadxp, emk tqxxa!" using 12 as key, I only get "ciphertext: iadxp, e". Does anybody know why does it encrypt only the first 8 characters and how should I change the code?

1

The goal is to encode each alpha in text. So why is the for loop based on the length of the key, strlen(argv[i])?

for (int i = 0, n = strlen(argv[i]); i < n; i++)

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

1
  • Thanks for the answer!
    – Red
    Mar 18 '19 at 4:57

You must log in to answer this question.

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