I have little problem with CS50 pset 2 vigenere cipher.

So this is my code


void encrypt(string word, string k);

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;
            key[i] = k[a];
            key[i] = word[i];

    for(int i = 0, n = strlen(word); i<n; 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));
            printf("%c", word[i]);

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.


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].


You must log in to answer this question.

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