-
Notifications
You must be signed in to change notification settings - Fork 0
/
vigenere.c
80 lines (63 loc) · 1.6 KB
/
vigenere.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
75
76
77
78
79
80
// A program that encrypts messages using Vigenère’s cipher
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
// check for 2 arguments only
if (argc != 2)
{
printf("Usage: ./vigenere k\n");
return 1;
}
// check if alphabetical
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (!isalpha(argv[1][i]))
{
printf("Usage: ./vigenere k\n");
return 1;
}
}
// from string to int
string k = argv[1];
int klen = strlen(k);
// check if the integer is non-negative
if (k < 0)
{
printf("Usage: ./vigenere k");
return 1;
}
else
{
// prompt the user for a code
string code = get_string("plaintext: ");
{
printf("ciphertext: ");
}
//key letter
for (int i = 0, j = 0, n = strlen(code); i < n; i++)
{
int key = k [j % klen];
//check if the letter is uppercase or lowercase then convert
if islower(code[i])
{
printf("%c", ((code[i] - 'a') + (tolower(key) - 'a')) % 26 + 'a');
j++;
}
else if isupper(code[i])
{
printf("%c", ((code[i] - 'A') + (toupper(key) - 'A')) % 26 + 'A');
j++;
}
//if its not a letter then print it without converting
else
{
printf("%c", code[i]);
}
}
printf("\n");
return 0;
}
}