-
Notifications
You must be signed in to change notification settings - Fork 0
/
caesar.c
49 lines (44 loc) · 1.17 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
# include <cs50.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <ctype.h>
int main (int argc, string argv[])
{
// take key as part of command line argument
if (argc !=2)
{
printf("Usage: ./caesar key \n");
return 1;
}
//make sure every character in argv[1] is a digit
for (int key = 0; key < strlen(argv[1]); key++)
{
if (isalpha(argv[1][key]))
{
printf("Usage: ./caesar key\n");
}
}
//int key
int key = atoi(argv[1]) % 26;
//prompt user for plaintest
string plaintext = get_string("Thy Brief: ");
//convert argv[1] from 'string' to 'int'
for (int i = 0, length = strlen(plaintext); i < length; i++)
{
if (!isalpha(plaintext[i]))
{
printf("%c", plaintext[i]);
continue;
}
//for each character in plaintext
//rotate the character if its a letter
int n = isupper(plaintext[i]) ? 65 : 97;
int pi = plaintext[i] - n;
int ci = (pi + key) % 26;
printf("%c", ci + n);
}
//printout coded message
printf("\n");
return 0;
}