-
Notifications
You must be signed in to change notification settings - Fork 409
/
vigenere.c
54 lines (44 loc) Β· 1022 Bytes
/
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <cs50.h>
bool is_valid_k(string k)
{
for (int i = 0; i < strlen(k); i++)
{
if (!isalpha(k[i]))
{
return false;
}
}
return true;
}
int main(int argc, string args[])
{
if (argc != 2 || !is_valid_k(args[1]))
{
printf("Usage: ./vigenere k\n");
return 1;
}
string k = args[1];
string plaintext = get_string("plaintext: ");
int k_len = strlen(k);
printf("ciphertext: ");
for (int i = 0, j = 0, n = strlen(plaintext); i < n; i++)
{
if (!isalpha(plaintext[i]))
{
printf("%c", plaintext[i]);
continue;
}
int ascii_offset = isupper(plaintext[i]) ? 65 : 97;
int pi = plaintext[i] - ascii_offset;
int kj = toupper(k[j % k_len]) - 65;
int ci = (pi + kj) % 26;
j++;
printf("%c", ci + ascii_offset);
}
printf("\n");
return 0;
}