0

I can not figure out why my cypertext is missing a letter when I use the key "bacon" and the plaintext: Meet me at the park at eleven am. The output I get is "Neg zf av uf pcx bt gzrwep oz" when it should be "Negh zf av huf pcfx bt gzrwep oz"

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

//get key from user
int main(int argc, string argv[]) {

//check to make sure argv is 2 and key is alphabetic
if(argc != 2) {
    printf("That is not a valid key.\n");
    return 1;
}

string key = argv[1];
int keylen = strlen(key);

for(int x = 0; x < keylen; x++){
    if (!isalpha(key[x])) {
        printf("That is not a valid key.\n");
        return 1;
    }
    key[x] = toupper(key[x]);
 }


//get plaintext from user
string ptext = get_string("plaintext:\n");

printf("ciphertext:");

int ptextlen = strlen(ptext);

//check to see if char is alphabetic and encrypt. then print cipertext
for(int x = 0, j = 0; x < ptextlen; x++) {
    if isalpha(ptext[x]) {
        if islower(ptext[x]) {
            printf("%c", ((ptext[x] - 97) + (key[j] - 65) % 26) + 97);
        } else {
            printf("%c", ((ptext[x] - 65) + (key[j] - 65) % 26) + 65);
        }
    j = (j + 1) % keylen;
    } else {
        printf("%c", ptext[x]);
    }

}
printf("\n");
return 0;

}

2
  • I did end up figuring it out. The order of operation was slightly off. I just needed another parenthesis.
    – MeaghanRH
    May 18, 2018 at 22:02
  • Great that you found the solution on your own. Self-answered questions are highly encouraged! Can you post as an answer and accept it (when the system allows) ? Otherwise, it will stay as an unanswered question forever.
    – Cliff B
    May 18, 2018 at 22:20

1 Answer 1

0
 //check to see if char is alphabetic and encrypt. then print cipertext
for(int x = 0, j = 0; x < ptextlen; x++) {
    if isalpha(ptext[x]) {
        if islower(ptext[x]) {
            printf("%c", (((ptext[x] - 97) + (key[j] - 65)) % 26) + 97);
        } else {
            printf("%c", (((ptext[x] - 65) + (key[j] - 65)) % 26) + 65);
        }
    j = (j + 1) % keylen;
    } else {
        printf("%c", ptext[x]);
    }

You must log in to answer this question.

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