-
Notifications
You must be signed in to change notification settings - Fork 0
/
vigenere.c
73 lines (71 loc) · 1.45 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
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("usage: ./vigenere k\n");
return 1;
}
string key = argv[1];
int ikey = strlen(key);
int nkey[ikey];
for (int i = 0; i < ikey; i++)
{
if (! isalpha(key[i]) )
{
printf("Alphabetic characters only.\n");
return 1;
}
else if ( isupper(key[i]) )
{
nkey[i] = key[i] - 'A';
}
else
{
nkey[i] = key[i] - 'a';
}
}
printf("plaintext: ");
string pt = get_string();
printf("ciphertext: ");
int j = ikey; // or j = 0;
for (int i = 0, ipt = strlen(pt); i < ipt; i++)
{
int ptkey = pt[i] + nkey[j % ikey];
if ( isupper(pt[i]) )
{
if (ptkey > 'Z')
{
printf("%c", ptkey - 26);
j++;
}
else
{
printf("%c", ptkey);
j++;
}
}
else if ( islower(pt[i]) )
{
if (ptkey > 'z')
{
printf("%c", ptkey - 26);
j++;
}
else
{
printf("%c", ptkey);
j++;
}
}
else
{
printf("%c", pt[i]);
}
}
printf("\n");
return 0;
}