-
Notifications
You must be signed in to change notification settings - Fork 0
/
vigenere
59 lines (51 loc) · 1.29 KB
/
vigenere
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
#include <stdlib.h>
#include <stdio.h>
#include <cs50.h> //gets string from user with GetString()
#include <ctype.h>
#include <string.h>
//takes in char a, and increments it by k if it is a letter
char crypt(char a, char k);
int main(int argc, string argv[])
{
if (argc!=2) //checks for parameters
{
printf("Invalid parameters.\n");
return 1;
}
string k = argv[1];
int klength = strlen(k);
for (int i=0; i<klength; i++) //checks that all key values are chars
{
if (!isalpha(k[i]))
{
printf("Invalid parameters. Contains non-characters.\n");
return 1;
}
}
string sentence = GetString();
for(int i=0, j=0, slength = strlen(sentence); i<slength; i++)
{
if (isalpha(sentence[i]))
{
sentence[i] = crypt(sentence[i], k[j%klength]);
j++;
}
}
printf("%s\n", sentence);
}
char crypt(char a, char k)
{
int base; //base allows for the use of MOD on letter values of 0-25
k= tolower(k); //converts k to proper offset value
k-=97;
if (isalpha(a))
{
if(islower(a))
base = 97;
else
base= 65;
return (a-base+k)%26+base;
}
else
return a;
}