0

Why do I only get the corresponding key for A and B and not c and d with my code?

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


int main(void)
{
    string key = "NQXPOMAFTRHLZGECYJIUWSKDVB";
    string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXZ";
    string plaintext = "ABcd";
    char str[] = "";
    int n = 0;
       printf("Ciphercore: \n");

for (int j = 0; j< strlen(plaintext); j++)
{
    for (int i = 0; i < strlen(alphabet); i++)
    {
        if(plaintext[j] == alphabet[i])
        {
            if(isupper(plaintext[j]))
            {
                printf("Input is is UPPERCASE %c\n", plaintext[i]);
                printf("Place in alphabet is %i\n", i+1);
                printf("Corresponding key is %c\n", key[i]);
            }
                else if (islower(plaintext[j]))
                {
                        printf("Input is is lowercase %c\n", plaintext[i]);
                        printf("Place in alphabet is %i\n", i+1);
                        printf("Corresponding key is %c\n", key[i]);
                }
        }   }
    }
}
1

Strings are always case sensitive. Therefore on comparing any lowercase letter with an uppercase letter, the answer is always false. You can now try two things. First method is to create a lowercase alphabet string. The second method is using strcasecmp, which is mentioned in speller of pset5. A third method also exists. For this, you have to get the ascii code of the letter. If it is uppercase then subtract it by 65 and use this to find the letter in the key. If it is lowercase then subtract it by 97. Also remember that you should preserve the original case of the plaintext.

If this helps, please check the tickmark.

1
  • Yes that worked, thanks!
    – Alexander
    Oct 30 '20 at 9:32

You must log in to answer this question.

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