0

I am getting an odd output and can't figure out why. I have tried using a debugger and tried different ways of approaching the problem.

int main(int argc, string argv[]) {

if (argc == 2)
{
    string key = argv[1]; 


    printf("plaintext: ");
    string plaintext = get_string();
    printf("ciphertext: ");
    int j = 0;
    for(int i = 0, n = strlen(plaintext) ; i < n; i++, j = (j+ 1)  % n)

    {

        char keyplace = key[j];

        if (isalpha(plaintext[i])){
                if(isalpha((unsigned char) plaintext[i]))
                {
                    if(isupper(plaintext[i] && isupper(keyplace)) )
                    {
                    //int alpha_index = alpha_index_up2 + 65;
                        printf("%c", ((plaintext[i] - 65 + key[i % n] - 65) % 26) + 97);
                }
                else if (islower(plaintext[i]) && islower(keyplace))
                {


                        printf("%c", ((plaintext[i] - 97 + key[i % n] - 97) % 26) + 65);
                }
                else if(isupper(plaintext[i] && islower(keyplace)) )
                {
                    printf("%c", (((plaintext[i] - 65) + (key[i % n] - 97 )) % 26) + 97) ;
                }
                else{
                    printf("%c", ((((plaintext[i] - 97) + key[i % n]  - 65)) % 26) + 65); 
                }
            }
        else
        {
            printf("%c", plaintext[i]);
            j--;
        }

        }
    }
printf("\n");
}

        else 
        {
            printf("Usage: ./caesar k");
            return 1;
        }
return 0;

}

1 Answer 1

0

With key[i % n], you probably mean keyplace or key[j]. You could get rid of the test whether keyplace is upper- or lowercase (and therefore go from four cases to two) by using toupper(keyplace) or tolower(keyplace), that way you already know whether the value is upper- or lowercase.

And you might want to add a test whether the key is actually alphabetic, as vigenère ciphers in that simple definition work on letters A-Z only.

You must log in to answer this question.

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