1

I give up, I can't make it work. Please kindly point me to a line where I make mistake.

// input validation

if (argc != 2)
{
    printf("Invalid argument. Please, try again\n");

    return 1;
}

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

    if (isalpha(letter) == 0)
    {
        printf("Invalid argument. Please, try again\n");
        break;
    }
}

string p = GetString();

//gets the text enciphered

for (int i = 0, len = strlen(p); i < len; i++)
{
    int key = argv[1][i];

    if (isupper(key))
    {
        key = key - 65;
    }

    if (islower(key))
    {
        key = key - 97;
    }

    int letter = p[i];

    if (isalpha(letter))
    {
        if (isupper(letter))
        {
            int a = ((letter - 65 + key) % 26 + 65);
            printf("%c", a);
        }

        if (islower(letter))
        {
            int a = ((letter - 97 + key) % 26 + 97);
            printf("%c",a);
        }
    }

    else
    {
        printf("%c", letter);
    }
}

printf("\n");

}

When I test for

Meet me at the park at eleven am

I get

Negh mq ni mon wodo uu reyqya mh

Instead of

Negh zf av huf pcfx bt gzrwep oz

1 Answer 1

0

The problem is that the key is being advanced to the next letter when it shouldn't. The code should only advance to the next letter when a plaintext letter is encoded. It should not be advanced for a space, number, punctuation or any other non-alpha character.

The underlying problem is that you are using the same index, i, to select both the plaintext letter to encode and the key letter to use. The plaintext and the key should have two separate and independent index variables. The plaintext index will increment for every character processed from the string to be encoded, but the key index will ONLY be incremented when a letter is encoded.

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