-
Notifications
You must be signed in to change notification settings - Fork 25
/
caesar.c
77 lines (68 loc) · 1.44 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
/*
https://cs50.harvard.edu/x/2022/psets/2/caesar/
*/
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
bool only_digits(string arg);
char rotate(char chr, int key);
int main(int argc, string argv[])
{
// Check for the argument count to be exactly 2
if (!(argc == 2))
{
printf("Usage: ./caesar key\n");
return 1;
}
// Check for the second argument to be a digit
if (!(only_digits(argv[1])))
{
printf("Usage: ./caesar key\n");
return 1;
}
// Get user input
string plaintext = get_string("plaintext: ");
// Print output
printf("ciphertext: ");
for (int i = 0, len = strlen(plaintext); i < len; i++)
{
printf("%c", rotate(plaintext[i], atoi(argv[1])));
}
printf("\n");
}
// Checks that the argument is only digits from 0 to 9
bool only_digits(string arg)
{
if (isdigit(arg[0]))
{
return true;
}
else
{
return false;
}
}
// Shifts 'char' by the 'key' value
char rotate(char chr, int key)
{
// if 'char' is a letter, shift it by 'key' value
if (isalpha(chr))
{
if (isupper(chr))
{
return (chr - 'A' + key) % 26 + 'A';
}
if (islower(chr))
{
return (chr - 'a' + key) % 26 + 'a';
}
return 0;
}
// if 'char' is anything else, return 'char' as is
else
{
return chr;
}
}