-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcaesar.c
More file actions
61 lines (53 loc) · 1.19 KB
/
Copy pathcaesar.c
File metadata and controls
61 lines (53 loc) · 1.19 KB
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
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
bool only_digits(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 (!only_digits(argv[1]))
{
printf("Usage: ./caesar key\n");
return 1;
}
int offset = atoi(argv[1]);
string input = get_string("plaintext: ");
const string lower = "abcdefghijklmnopqrstuvwxyz";
const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const int max = 26;
printf("ciphertext: ");
for (int i = 0; i < strlen(input); i++)
{
char current = input[i];
if (isalpha(current))
{
char base = isupper(current) ? 'A' : 'a';
int idx = (current - base + offset) % max;
printf("%c", isupper(current) ? upper[idx] : lower[idx]);
}
else
{
printf("%c", current);
}
}
printf("\n");
return 0;
}
bool only_digits(string s)
{
for (int i = 0; s[i] != '\0'; i++)
{
if (!isdigit(s[i]))
{
return false;
}
}
return true;
}