I got my Vigenere cipher to work except for the part where you are supposed to skip over a space or symbol while maintaining your position in the key. In other words, a space or symbol is being assigned a char from the key array.
It looks like this (second line is the key):
This is CSfifty
abcabcabcabcabc
When it should look like this:
This is CSfifty
abca bc abcabca
Here is my code so far:
#include<stdio.h>
#include<cs50.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int main(int argc, string argv[])
{
string key = argv[1];
int keylen = strlen(argv[1]);
// key position validation
if (argc != 2)
{
return -1;
}
// index into string key
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
// key alpha validation
if (!isalpha(key[i]))
{
return -1;
}
// zero key
key[i] = tolower(key[i]);
key[i] = key[i] - 97;
}
// plain text input
printf("Plain text:\n");
string plain = GetString();
// encipher
for(int k = 0, p = strlen(plain); k < p; k++)
{
if(isalpha(plain[k]))
{
if(islower(plain[k]))
{
printf("%c", (( (plain[k] - 97) + (key[k % keylen]) ) % 26 + 97));
}
else if(isupper(plain[k]))
{
printf("%c", (( (plain[k] - 65) + (key[k % keylen]) ) % 26 + 65));
}
}
else if(!isalpha(plain[k]))
{
printf("%c", plain [k]);
}
}
printf("\n");
The code I just pasted does not even try to accommodate the space problem. I just pasted the version that works right now. I've been staring at my computer for three hours trying to figure out the problem but nothing seems to work. The closest I got to progress was when I created a separate for loop to create a new array that is the length of the plaintext and populated with the key (repeated to fill the length of the array). I was attempting to map the "plain-text-length key" before using it to print out the cipher text rather than enciphering the plaintext in real time in the cipher printf line as shown above. I tried subtracting from the counter and subtracting from the terminal int (to equal out the fact that I turned the clock back by 1.) But for some reason that ended up with the key repeating a single letter after encountering the space or symbol. (btw the reason why I made plainlenkey[j] = 'a' was so that the key didn't change the space or symbol in the cipher text since 'a' equaled 0.)
Here is what the for loop looked like:
char plainlenkey[strlen(plain)];
for(int j = 0, n = strlen(plain); j < n; j++)
{
if(isalpha(plain[j]))
{
plainlenkey[j] = key[j % keylen];
}
else if(!isalpha(plain[j]))
{
plainlenkey[j] = 'a';
n--;
j--;
}
}
And result looked something like:
This is CSfifty
ababaaaaaaaaaaa
I know this is a lot... so thanks in advance!