I have been futzing with this for a couple of weeks. I actually put it away while I did pset3 but, having come back to it, I'm still stuck. I spent an entire day on it this weekend and tried adding a loop, moving the loop, restructuring the if statements, etc. I'm pretty sure I went in circles and I can't figure out how to create an index for the key. I feel like this should work and it compiles but it doesn't print out any letters for the ciphertext. When I type "hello" I get "".
Can someone help me understand why this doesn't work and give me a tip on how to establish an index for the key so it will iterate one letter at a time for only alpha characters?
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, string argv[])
{
//Ensure that user enters 2 command line arguments (argv[0] - program name and argv[1] - the key number)
if (argc != 2)
{
printf("Enter the file name and a key.\n");
return 1;
}
//Increment across key, letter by letter
string key = argv[1];
for (int j = 0, o = strlen(key); j < o; j++)
//Ensure argv[1] is alpha
while (!(isalpha (key[j]) != '\0'))
{
printf("Key must be alpha.\n");
return 1;
}
//Get plaintext string that user wants converted to ciphertext
string plaintext = get_string("plaintext: ");
printf("ciphertext: ");
//Increment across user's plaintext entry, letter by letter.
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
if (isalpha(plaintext[i]))
{
for (int k = key[0], l = strlen(key); k < l; k++)
//Ensure capital letters stay capital and lowercase stay lower.
//encipher, shifting each letter of plaintext string one at a time by the key.
if (isupper(plaintext[i]))
{
printf("%c", (((plaintext[i] - 'A' + (toupper(key[k % l])) - 'A')) % 26) + 'A');
}
else if (islower(plaintext[i]))
{
printf("%c", (((plaintext[i] - 'a' + (tolower(key[k % l])) - 'a')) % 26) + 'a');
}
// Ensure non alpha characters stay as they are.
else
{
printf("%c", plaintext[i]);
}
}
else
{
printf("%c", plaintext[i]);
}
}
printf("\n");
return 0;
}