Skip to content

Instantly share code, notes, and snippets.

@tommymalmqvist
Created September 25, 2014 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommymalmqvist/78aecef035538b564191 to your computer and use it in GitHub Desktop.
Save tommymalmqvist/78aecef035538b564191 to your computer and use it in GitHub Desktop.
vigenere.c
#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