-
Notifications
You must be signed in to change notification settings - Fork 0
/
caesar.c
80 lines (72 loc) · 1.51 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
79
80
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int isInteger(string s);
void cipher(string argv, string s);
int main(int argc, string argv[])
{
if (argc != 2 || isInteger(argv[1]) == 0)
{
printf("Usage: ./caesar key\n");
return 1;
}
string plaintext = get_string("plaintext: ");
cipher(argv[1], plaintext);
return 0;
}
// Functions
int isInteger(string s)
{
for (int i = 0; i < strlen(s); i++)
{
if (isdigit(s[i]) == 0)
{
return 0;
}
}
return 1;
}
void cipher(string argv, string s)
{
char ciphertext[strlen(s)];
int key = atoi(argv);
if (key >= 26)
{
key %= 26;
}
for (int i = 0; i < strlen(s); i++)
{
if (isalpha(s[i]) == 0)
{
ciphertext[i] = s[i];
}
else
{
if (isupper(s[i]))
{
if (s[i] + key > 90)
{
ciphertext[i] = s[i] + key - 26;
}
else
{
ciphertext[i] = s[i] + key;
}
}
if (islower(s[i]))
{
if (s[i] + key > 122)
{
ciphertext[i] = s[i] + key - 26;
}
else
{
ciphertext[i] = s[i] + key;
}
}
}
}
printf("ciphertext: %s\n", ciphertext);
}