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.