0

I can't solve the problem with key "hello, world!" and understand why it appears.

enter image description here

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

int main (int argc, string argv[])
{
if (argc > 2 || argc < 2)
{
    printf("Eror\n");
    return 1;
}

for (int i = 0; i < strlen(argv[1]); i++)
{
    if (isalpha(argv[1][i]) == 0)
    {
        printf("Eror\n");
        return 1;
    }
}

printf("Give me your msg\n");
string msg = get_string();
int j=0;
printf("ciphertext:");
    for (int i = 0, lengthmsg = strlen(msg); i < lengthmsg; i++)
    {
        j = j % strlen(argv[1]);

        if (isupper(msg[i]) && isupper(argv[1][j]))
            printf("%c", (( (msg[i] - 65) + (argv[1][j] - 65) ) % 26) + 65);
        else if (islower(msg[i]) && islower(argv[1][j]))
            printf("%c", (( (msg[i] - 97) + (argv[1][j] - 97) ) % 26) + 97);
        else if (islower(msg[i]) && isupper(argv[1][j]))
            printf("%c", (( (msg[i] - 97) + (argv[1][j] - 65) ) % 26) + 97);
        else if (isupper(msg[i]) && islower(argv[1][j]))
            printf("%c", (( (msg[i] - 65) + (argv[1][j] - 97) ) % 26) + 65);
        else
            printf("%c",msg[i]);
        j++;
    }
    printf("\n");
    return 0;
}

1 Answer 1

1

This is a somewhat common error for this exercise.

The code uses j as an index for the key. The problem is that j is incremented for EVERY character that is processed. The key index should ONLY be incremented when a letter is processed and never when a non-letter such as a space or punctuation is processed.

Because of this, the key gets out of synch with the letters to be encoded, so the wrong key letter is being used.

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

1
  • Thank you so much for the answer. I fixed it like this : if (isalpha(msg[i])) {j++;} and it all worked.
    – Ihor Kozar
    Dec 2, 2018 at 9:37

You must log in to answer this question.

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