Created
September 25, 2014 11:38
-
-
Save tommymalmqvist/78aecef035538b564191 to your computer and use it in GitHub Desktop.
vigenere.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <cs50.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <ctype.h> | |
int main(int argc, char *argv[]) | |
{ | |
if (argc != 2) | |
{ | |
printf("usage: %s <keyword>\n", argv[0]); | |
return 1; | |
} | |
char* keyword = argv[1]; | |
int keylen = strlen( argv[1] ); | |
int transform; | |
char* enc; | |
// check if keyword is all letters | |
for (int i = 0; i < keylen; i++) | |
{ | |
char letter = keyword[i]; | |
if (!isalpha(letter)) | |
{ | |
printf("usage: %s <keyword>\n", argv[0]); | |
return 1; | |
} | |
} | |
// magic | |
printf("Input text: "); | |
char* text = GetString(); | |
int textLen = strlen(text); | |
int m = 0; // variable is used to stand against non alphabetical chars that increments i++ and at the same time breaking the cipher | |
for (int i = 0; i < textLen; i++) | |
{ | |
int textLetter = text[i]; | |
int modulo = (m%keylen); | |
m += 1; | |
int keyLetter = keyword[modulo]; | |
int newLetter = 0; | |
if (isalpha(textLetter)) | |
{ | |
if (isupper(textLetter)) | |
{ | |
if(islower(keyLetter)) | |
{ | |
keyLetter -= 32; | |
int newLetter = (textLetter + keyLetter) % 26 + 'A'; | |
printf("%c", newLetter); | |
} | |
else | |
{ | |
int newLetter = (textLetter + keyLetter) % 26 + 'a'; | |
printf("%c", newLetter); | |
} | |
} | |
if (islower(textLetter)) | |
{ | |
textLetter -= 32; | |
if(isupper(keyLetter)) | |
{ | |
int newLetter = (textLetter + keyLetter) % 26 + 'A'; | |
printf("%c", newLetter); | |
} | |
else | |
{ | |
keyLetter -= 32; | |
int newLetter = (textLetter + keyLetter) % 26 + 'a'; | |
printf("%c", newLetter); | |
} | |
} | |
} | |
else | |
{ | |
newLetter = textLetter; | |
m -= 1; | |
} | |
printf("%c", newLetter); | |
} | |
printf("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment