-
Notifications
You must be signed in to change notification settings - Fork 0
/
caesar.c
67 lines (59 loc) · 1.25 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
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool only_digits(string s);
char rotate(char c, int n);
int main(int argc, string argv[])
{
// Make sure the program only accepts a single command-line argument, a non-negative integer (k)
if (argc == 1 || argc > 2 || only_digits(argv[1]) == false)
{
printf("Usage: ./caesar key\n");
return 1;
}
else
{
int key = atoi(argv[1]);
string plaintext = get_string("plaintext: ");
printf("ciphertext: ");
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
printf("%c", rotate(plaintext[i], key));
}
printf("\n");
return 0;
}
}
// Function to make sure the argument is an integer
bool only_digits(string s)
{
bool flag = true;
for (int i = 0, n = strlen(s); i < n; i++)
{
if (isdigit(s[i]))
{
flag = true;
}
else
{
flag = false;
break;
}
}
return flag;
}
char rotate(char c, int n)
{
int p;
if (isupper(c))
{
c = ((int)c - 65 + n) % 26 + 65;
}
else if (islower(c))
{
c = ((int)c - 97 + n) % 26 + 97;
}
return c;
}