-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaesar.c
78 lines (73 loc) · 1.64 KB
/
caesar.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//Prototype
int encipher(string plaintext, int key);
int test_arguments(int arguments, string key[]);
// Confirms there are args included to run the program
int main(int argc, string argv[])
{
int test = test_arguments(argc, argv);
if (test)
{
return test;
}
else
{
//Promting for a plaintext
string plaintext = get_string("plaintext: ");
int key = atoi(argv[1]);
return encipher(plaintext, key);
}
}
//testing args
int test_arguments(int arguments, string key[])
{
//Confirming args are 2
if (arguments != 2)
{
printf("Usage: ./substitution key.\n");
return 1;
}
for (int i = 0, n = strlen(key[1]); i < n; i++)
{
if (isalpha(key[1][i]))
{
printf("Usage: ./caesar key.\n");
return 1;
}
}
return 0;
}
//enciphering text and key
int encipher(string plaintext, int key)
{
printf("ciphertext: ");
char ci;
int n = strlen(plaintext);
char ciphertext[n];
for (int i = 0; i < n; i++)
{
int c = plaintext[i];
//Checking if the char is alphabet
if (isalpha(c))
{
ci = c + key % 26;
bool test_boundaries = islower(ci) || isupper(ci);
if (!test_boundaries)
{
ci -= 26;
}
}
else
{
ci = c;
}
ciphertext[i] = ci;
}
// Returns an error message if the code isn't executed in proper format
printf("%s\n", ciphertext);
return 0;
}