-
Notifications
You must be signed in to change notification settings - Fork 0
/
caesar.c
63 lines (54 loc) · 1.03 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
#include <cs50.h>
#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool digits_only(string s);
char rotate(char c, int key);
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
if (!digits_only(argv[1]))
{
printf("Argument must be an integer.\n");
return 1;
}
int key = atoi(argv[1]);
string plain_text = get_string("plaintext: ");
printf("ciphertext: ");
int n = strlen(plain_text);
for (int i = 0; i < n; i++)
{
printf("%c", rotate(plain_text[i], key));
}
printf("\n");
return 0;
}
bool digits_only(string s)
{
for (int i = 0; i < strlen(s); i++)
{
if (!isdigit(s[i]))
{
return false;
}
}
return true;
}
char rotate(char c, int key)
{
if (isalpha(c))
{
char base = islower(c) ? 'a' : 'A';
return (c - base + key) % 26 + base;
}
else
{
return c;
}
}