0

I feel like I'm pretty close with this one, but I can't find where the wraparound is messing up. Any idea where I'm going wrong?

Expected: $ ./vigenere ABC plaintext: HELLO ciphertext: HFNLP

Actual: $./vigenere ABC plaintext: HELLO ciphertext: HFNO

or, strangely: $./vigenere AbC plaintext: Hello ciphertext: Hfnop

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

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


string k = argv[1];
int cipher_upper;
int cipher_lower;
int i;
int j;
int p_upper;
int p_lower;
int ascii_A = 65;
int ascii_a = 97;


if (argc != 2) {
    printf("Please enter only one command line argument.\n");
    return 1;
}

for (int c = 0; c < strlen(k); c++) {
    if (!isalpha(k[c])) {
        printf("Usage: ./vigenere k\n");
        return 1;
    }
}// end for loop to check for alpha characters only in key

printf("plaintext: ");
string p = get_string();
int p_len = strlen(p);
int k_len = strlen(k);

//iterate through characters in plaintext
for (i = 0, j = 0; i < p_len; i++, j++) {
    //skips over non-alpha characters, ciphers uppercase characters
    if (isalpha(p[i])) {
    if (isupper(p[i])) {
            p_upper = p[i] - ascii_A;
                if (isupper(k[j])) {
                cipher_upper = ((p_upper + ((k[j] - ascii_A))) % 26) + ascii_A;
                j = j % k_len;
                printf("%c", cipher_upper);
                }

                if (islower(k[j])) {
                cipher_upper = ((p_upper + ((k[j] - ascii_a))) % 26) + ascii_A;
                j = j % k_len;
                printf("%c", cipher_upper);
                }

    } // end is upper plaintext

    if (islower(p[i])) {
            p_lower = p[i] - ascii_a;
                if (isupper(k[j])) {
                cipher_lower = ((p_lower + ((k[j] - ascii_A))) % 26) + ascii_a;
                j = j % k_len;
                printf("%c", cipher_lower);
                }
                if (islower(k[j])) {
                cipher_lower = ((p_lower + ((k[j] - ascii_a))) % 26) + ascii_a;
                j = j % k_len;
                printf("%c", cipher_lower);
                }
    } // end is lower plaintext
} //end is alpha

else {
    printf("%c", p[i]);
}
} //end for loop plaintext
printf("\n");

} //end main
0

You should not increment j for non-letters. Also, j = j % k_len comes too late, has to be before any k[j] using this j.

Where do you print the string ciphertext:?

You must log in to answer this question.

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