0

I have little problem with CS50 pset 2 vigenere cipher.

So this is my code

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


void encrypt(string word, string k);


//main
int main(int argc, string argv[]){
    if(argc != 2){
        printf("You must enter the key!\n");
        return 1;
    }
        string k = argv[1];

        string word = GetString();
        encrypt(word, k);
}


//encrypt function
void encrypt(string word, string k){
    int m = strlen(k);
    string key = word;

    int a = 0;
    for(int i = 0,  n = strlen(word); i<n; i++){
        a = a%m;
        if(isalpha(word[i])){
            key[i] = k[a];
        }else{
            key[i] = word[i];
            a=a-1;
        }
        a++;
    }
    printf("%s\n",word);
    printf("%s\n",key);


    for(int i = 0, n = strlen(word); i<n; i++){
        if(isupper(word[i])){
            printf("%c", toupper(((word[i]-65+key[i])%26)+65));
        }else if(islower(word[i])){
            printf("%c", tolower(((word[i]-97+key[i])%26)+97));
        }
        else{
            printf("%c", word[i]);
        }
    }
    printf("\n");
}

This is the input

./vigenere bacon
Meet me at the park at eleven am

This is the output

baco nb ac onb acon ba conbac on
baco nb ac onb acon ba conbac on
Hvtxv tv tx vtv txvt vt xvtvtx vt

Why did the variable word become set of bacon key? Many thanks in advance.

1

I think the line string key = word; is not doing what you think it is doing. Define the stringkey and then use strcpy to copy the contents of word into key.

The way you are doing it, you are defining key to point to the same address as word so changing key[0] is the same thing as changing the value at word[0].

1

You must log in to answer this question.

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