mirror of https://github.com/me50/kukemuna.git
This commit is contained in:
commit
a1c1761831
|
|
@ -0,0 +1,86 @@
|
|||
#include <cs50.h>
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
int key_to_int_reduced(string s_key);
|
||||
void rotate(string plaintext, int i_key);
|
||||
|
||||
int main(int argc, string argv[])
|
||||
{
|
||||
// Print usage and exit if argc is not 2 or key is not integer
|
||||
if (argc != 2 || key_to_int_reduced(argv[1]) < 0)
|
||||
{
|
||||
printf("Usage: ./caesar key\n");
|
||||
return 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
string s_key = argv[1];
|
||||
int i_key = key_to_int_reduced(s_key);
|
||||
string plaintext = get_string("plaintext: ");
|
||||
rotate(plaintext, i_key);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Convert a string of numbers to integer
|
||||
int key_to_int_reduced(string s_key)
|
||||
{
|
||||
int key = 0;
|
||||
|
||||
// Iterate each string element
|
||||
for (int i = 0; i < strlen(s_key); i++)
|
||||
{
|
||||
if (isdigit(s_key[i]))
|
||||
{
|
||||
key += ((int) s_key[i] - 48);
|
||||
if (i < strlen(s_key) - 1)
|
||||
{
|
||||
key *= 10;
|
||||
}
|
||||
}
|
||||
// Cancel if not digit
|
||||
else
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// Reduce key size to < 26
|
||||
while (key >= 26)
|
||||
{
|
||||
key %= 26;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
void rotate(string plaintext, int i_key)
|
||||
{
|
||||
printf("ciphertext: ");
|
||||
|
||||
// Iterate each plaintext element
|
||||
for (int i = 0; i < strlen(plaintext); i++)
|
||||
{
|
||||
// Apply key for text characters only
|
||||
if (isalpha(plaintext[i]))
|
||||
{
|
||||
// Rollover and rotate characters, upper- and lowercase
|
||||
if ((isupper(plaintext[i]) && plaintext[i] + i_key > 90) || (islower(plaintext[i]) && plaintext[i] + i_key > 122))
|
||||
{
|
||||
printf("%c", plaintext[i] + i_key - 26);
|
||||
}
|
||||
// Rotate characters
|
||||
else
|
||||
{
|
||||
printf("%c", plaintext[i] + i_key);
|
||||
}
|
||||
}
|
||||
// Leave non-alphanumerics as-is
|
||||
else
|
||||
{
|
||||
printf("%c", plaintext[i]);
|
||||
}
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
Loading…
Reference in New Issue