0

I Don't know how to make code work if key is lowercase and text uppercase and vice-versa. Before I considered case sensitivity my code would work except for a few letters. Now it wont output full ciphertext. Can anybody tell me what I am not seeing?

for(int i = 0, n = strlen(text); i < n; i++)

        if(isalpha(text[i]))
        {
            if(isupper(text[i]))
            {
                //char cipher = (text[i] - 'A' + key[j % k_len] - 'A') % 26; 
                if(isupper(key[j]))
                {
                   char cipher = (text[i] - 'A' + key[j % k_len] - 'A') % 26;
                    printf("%c", cipher + 'A');
                    j++;
                }
                if(islower(key[j]))
                {
                    char cipher = (text[i] - 'A' + key[j % k_len] -'a') % 26;
                    printf("%c", cipher + 'a');
                    j++;
                }
            }
            if(islower(text[i]))
            {
                //char cipher = (text[i] - 'a' + key[j % k_len] - 'a') % 26;
                if(isupper(key[j]))
                {
                   char cipher = (text[i] - 'a' + key[j % k_len] - 'A') % 26;
                    printf("%c", cipher + 'a');
                    j++;
                }
                if(islower(key[j]))
                {
                   char cipher = (text[i] - 'a' + key[j % k_len] -'a') % 26;
                   printf("%c", cipher + 'a');
                   j++;
                }
            }
        }
        else
        {
            printf("%c", text[i]);

        }
     printf("\n");
}
1
  • Can you post your whole code? I'm getting way too many errors upon compiling this. Aug 7 '16 at 19:57
0

There are several problems here. First, there is a typo in one of the four code blocks. I'll let you find that one on your own. ;-)

Next, look at the following:

if(isupper(key[j]))

Since j increases with every letter encoded, what happens when j is greater than the length of key?

Finally, when a letter is encoded, j is incremented. But consider what happens when the key letter is uppercase and the next key char is lower case. Because j is incremented when the first test case is processed, both tests for the key will be true, so both cases will be executed. Maybe an else if should be considered?

THis should take care of most of your problems. If this answers your question, please click on the check mark to accept. Let's keep up n forum maintenance. ;-)

You must log in to answer this question.

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