#include <stdio.h>
#include <string.h>
#include <cs50.h>
#include <ctype.h>
bool check_alpha(string k);
// this code is for if the plain text has only one long string without space in between
int main(int argc, string argv[])
{
if (argc != 1)
{
// get key from command line argument
string key = argv[(argc - 1)];
int l_key = strlen(key);
// check if the key string is alphabetical
bool y = check_alpha(key);
if ( y )
{
// prompt for plaintext
string text = get_string("Please type your text: ");
int l_text = strlen(text);
// for each character in the plaintext string
if (l_text!= 0)
{
for (int i=0; i<l_text; i++)
{
// if alphabetic
if (isalpha(text[i]))
{
// preserve case
if(isupper(text[i]))
{
// shift plaintext character by according char in key string
// convert the according char in key string to alphabetical index
int k = key[(i%l_key)] - 'a';
// convert the according char in plain text string to alphabetical index
int p = text[i] - 'A';
// convert to ciphertext letter: c = (p+k)%26
int c = (p+k)%26;
// convert to ascii for upper case char
text[i] = c + 'A';
}
else
{
// shift plaintext character by according char in key string
// convert the according char in key string to alphabetical index
int k = key[(i%l_key)] - 'a';
// convert the according char in plain text string to alphabetical index
int p = text[i] - 'a';
// convert to ciphertext letter: c = (p+k)%26
int c = (p+k)%26;
// convert to ascii for upper case char
text[i] = c + 'a';
}
}
}
// print ciphertext
printf("The crypto-text is: %s\n", text);
}
}
else
{
printf("The key string is not alphabetical.\n");
}
}
}
bool check_alpha(string k)
{
int l=strlen(k);
int i=0;
while ( (k[i] != '\0') && (isalpha(k[i])) )
{
i++;
}
if ( i == l )
{
return true;
}
else
{
return false;
}
}