-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvigenere.c
68 lines (58 loc) · 1.61 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
// Vigenere cipher
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(int argc, string argv[])
{
// Signifies an error when user does not input two command-line arguments
if (argc != 2)
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
else
{
// Sends an error when program receives a non-alphabetical character
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (!isalpha(argv[1][i]))
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
}
}
// Store key as string and get length
string key = argv[1];
int keyLen = strlen(key);
// Get text to encode
string pt = get_string("plaintext: ");
printf("ciphertext: ");
// Converts plaintext to ciphertext
for (int i = 0, j = 0, n = strlen(pt); i < n; i++)
{
// Get key for this letter
int letterKey = tolower(key[j % keyLen]) - 'a';
// Keep case of letter
if (isupper(pt[i]))
{
// Get modulo number and add to appropriate case
printf("%c", 'A' + (pt[i] - 'A' + letterKey) % 26);
// Only increment j when used
j++;
}
else if (islower(pt[i]))
{
printf("%c", 'a' + (pt[i] - 'a' + letterKey) % 26);
j++;
}
else
{
// Return unchanged
printf("%c", pt[i]);
}
}
printf("\n");
return 0;
}