Skip to content

Instantly share code, notes, and snippets.

@progapandist
Created May 19, 2015 13:32
Show Gist options
  • Save progapandist/4239da3e19ddbc5d2cf1 to your computer and use it in GitHub Desktop.
Save progapandist/4239da3e19ddbc5d2cf1 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
// Prototyping alpabetical check function.
int checkalpha(string k);
int main(int argc, string argv[])
{
// Check if there is an argument.
if (argc == 1)
{
printf("You should provide an argument!\n");
return 1;
}
// Store a keyword as an argument.
string wordkey = argv[1];
/* Initialising integer array to store numeric values
* of characters inside keyword.
*/
int numkey[strlen(wordkey)];
/* Checking if there's no more then one argument
* with alphabetical-only characters
*/
if (argc == 2 && checkalpha(wordkey) == 0)
{
// Converting lowercase characters in the key to numerical values.
for (int i = 0; i < strlen(wordkey); i++)
{
numkey[i] = (islower(wordkey[i])) ?
(wordkey[i]) - 97 : (wordkey[i]) - 65;
}
// Ask user for a message to encode.
string msg = GetString();
char msgc[strlen(msg)];
int i = 0;
int j = 0;
// Iterating through plain message.
while (msg[i] != '\0')
{
// Routine for lowercase.
if (islower(msg[i]))
{
msgc[i] = msg[i] + numkey[j] > 122 ?
msg[i] - 26 + numkey[j] : msg[i] + numkey[j];
printf("%c", msgc[i]);
j++;
if (j > strlen(wordkey) - 1)
{
j = 0;
}
}
// Routine for uppercase.
else if (isupper(msg[i]))
{
msgc[i] = msg[i] + numkey[j] > 90 ?
msg[i] - 26 + numkey[j] : msg[i] + numkey[j];
printf("%c", msgc[i]);
j++;
if (j > strlen(wordkey) - 1)
{
j = 0;
}
}
// Do nothing if non-alphabetical.
else
{
msgc[i] = msg[i];
printf("%c", msg[i]);
}
i++;
}
printf("\n");
return 0;
}
// Fall through if argument conditions are not respected.
else
{
printf("You need to provide exactly one argument ");
printf("to code your message.\n");
printf("Alphabetic characters only!\n");
return 1;
}
}
// Function to check if all characters in string array are alphabetical.
int checkalpha(string k)
{
int n = 0;
for (int i = 0; i < strlen(k); i++)
{
if (isalpha(k[i]))
{
n = 0;
}
else
{
n = 1;
}
}
return n;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment