-
Notifications
You must be signed in to change notification settings - Fork 0
/
caesar.c
63 lines (57 loc) · 1.58 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
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
//Checking if command line argument is valid
int key = 0;
if (argc == 2)
{
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (argv[1][i] < '0' || argv[1][i] > '9')
{
printf("Usage: ./caesar key\n");
return 1;
}
// converting string into integer
key = atoi(argv[1]);
printf("Key: %i\n", key);
}
}
else
{
// Handling lack of argument or too many of them
printf("Usage: ./caesar key\n");
return 1;
}
// Prompting for plain text
string plaintext = get_string("plaintext: ");
// Initialising empty string(array) for cypher text
char ciphertext[strlen(plaintext)];
printf("ciphertext: ");
// Iterating over string and checking for lover and upper case characters
for (int i = 0, n = strlen(plaintext); i < n; i++)
{
if (islower(plaintext[i]))
{
ciphertext[i] = (plaintext[i] - 'a' + key) % 26;
printf("%c", ciphertext[i] + 'a');
}
else if (isupper(plaintext[i]))
{
ciphertext[i] = (plaintext[i] - 'A' + key) % 26;
printf("%c", ciphertext[i] + 'A');
}
else
{
// Non aplhabetical character are not to be crypted
ciphertext[i] = plaintext[i];
printf("%c", ciphertext[i]);
}
}
printf("\n");
}