Reputation: 55
I have been working on this Vigenere cipher for about 8 hours straight. Can you please help me? I think that main problem is around the algorithm - I don't know how to utilize the keylength (I know I need to get the mod of it somehow).
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Bad!");
return 1;
}
int keylen = strlen(argv[1]);
char *key = argv[1];
for (int i = 0; i < keylen; i++)
{
if(isupper(key[i]))
{
key[i] = key[i]-65;
}
else if(islower(key[i]))
{
key[i] = key[i]-97;
}
}
printf("Plaintext: ");
string p = GetString();
int k = 0;
for (int i = 0; i < strlen(p); i++)
{
if(isalpha(p[i]))
{
if(isupper(p[i]))
{
p[i] = ((p[i]-65)+(key[k % keylen]))%26 + 65;
}
else if(islower(p[i]))
{
p[i] = ((p[i]-97)+(key[k % keylen]))%26 + 97;
}
k++;
}
else
{
//I need to skip over antyhing that isn't a letter
p[i] = p[i];
}
}
printf("Ciphertext: %s\n", p);
}
Upvotes: 0
Views: 5658
Reputation: 34829
The first for
loop has a problem. The condition is checking for i > keylen
when it should be checking for i < keylen
.
Also when computing the next output value, the steps should be
(p[i]-'A') results in a number between 0 and 25
adding (key[i % keylen]) results in a number between 0 and 50
apply modulo 26 so the number is between 0 and 25 (this is the missing step)
then add 'A' to get the output
Note: Avoid using hard-coded numbers for character constants. For example, use 'A'
instead of 65, and 'a'
instead of 97.
Upvotes: 3