The crux is at the last part where I've commented "CONVERT PLAINTEXT TO CIPHERTEXT" The variable asciiValue holds the, well, the asciiValue of the enciphered character. As you can see, I've used the modulo to not let it overflow to anything other than alphabets.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main (int argc, string argv[])
{
//Create int key to be initialized later.
int key;
////////////////////////////////////
//CHECKING FOR A VALID KEY PASSED IN
//Check if 2 arguments passed in
if (argc != 2)
{
printf("One command line argument allowed\n");
return 1;
}
else
{
//Check if all the characters are digits
for (int i = 0, stringLength = strlen(argv[1]) ; i < stringLength ; i++)
{
if (!isdigit(argv[1][i]))
{
printf("Please pass in a valid INTEGER\n");
return 1;
}
}
//If an integer passed as key,
//convert it to int and store in variable key
key = atoi(argv[1]);
//If key is negative, return 1
if (key < 0)
{
printf("Key has to be a POSITIVE INTEGER\n");
return 1;
}
}
////////////////////////////////////
//GETTING PLAINTEXT FROM USER
string plaintext = get_string("Plaintext: ");
////////////////////////////////////
//CONVERT PLAINTEXT TO CIPHERTEXT
printf("Ciphertext: ");
for (int i=0, stringLength = strlen(plaintext) ; i < stringLength ; i++)
{
if (isalpha(plaintext[i]))
{
int asciiValue = plaintext[i]+key%26;
printf("%c",asciiValue);
}
else
{
printf("%c", plaintext[i]);
}
}
}
And on another side, I'm still confused why did I even use isalpha() function instead of isupper() and islower() since they both exist at different parts of the ASCII table. But it still does make a little sense especially since the code works fine, except it prints out non-alphabetic characters when it passes z/Z.