forked from RaduStoian/Harvard-CS50-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
(week2) - caesar.c
75 lines (58 loc) · 2 KB
/
(week2) - 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
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
// only accepts 1 arguments
if (argc != 2)
{
printf("Usage ./caesar key\n");
return 1;
}
else
{
// checks to see if each character is a digit
for (int i = 0, n = strlen(argv[1]) ; i < n; i++)
{
if (!isdigit(argv[1][i]))
{
printf("Usage ./caesar key\n");
return 1;
}
}
// if only 1 argument and all chars are digits, convert to int and print
int inputKey = atoi(argv[1]);
//getting input string from user
string input = get_string("plaintext: ");
// running through inputed string
for (int i = 0; i < strlen(input); i++)
{
//if char is not letter, then leave the same
if (!isalpha(input[i]))
{
}
else
{
//if letter is going out of bounds,
if ((input[i] >= 65 && input[i] <= 90) && input[i] + inputKey > 90)
{
//wrap back around.
input[i] = ((((input[i] + inputKey) - 65) % 26) + 65);
}
//if letter is going out of bounds,
else if ((input[i] >= 97 && input[i] <= 122) && input[i] + inputKey > 122)
{
//wrap back around.
input[i] = ((((input[i] + inputKey) - 97) % 26) + 97);
}
else
{
input[i] += inputKey;
}
}
}
printf("ciphertext: %s\n", input);
return 0;
}
}