Last active
December 6, 2019 10:33
-
-
Save AnimeshRy/3cf26209006a91fc092a59af85deaa72 to your computer and use it in GitHub Desktop.
CS50 Vigenere 2019
This file contains hidden or 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 <cs50.h> | |
#include <ctype.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
int main(int argc, string argv[]) | |
{ | |
// Check if correct # of arguments given | |
if (argc != 2) | |
{ | |
printf("Usage: ./vigenere keyword\n"); | |
return 1; | |
} | |
else | |
{ | |
for (int i = 0, n = strlen(argv[1]); i < n; i++) | |
{ | |
if (!isalpha(argv[1][i])) | |
{ | |
printf("Usage: ./vigenere keyword"); | |
return 1; | |
} | |
} | |
} | |
// Store key as string and get length | |
string k = argv[1]; | |
int kLen = strlen(k); | |
// Get text to encode | |
string p = get_string("PLaintext: "); | |
printf("Ciphertext: "); | |
// Loop through text | |
for (int i = 0, j = 0, n = strlen(p); i < n; i++) | |
{ | |
// Get key for this letter | |
int letterKey = tolower(k[j % kLen]) - 'a'; | |
// Keep case of letter | |
if (isupper(p[i])) | |
{ | |
// Get modulo number and add to appropriate case | |
printf("%c", 'A' + (p[i] - 'A' + letterKey) % 26); | |
// Only increment j when used | |
j++; | |
} | |
else if (islower(p[i])) | |
{ | |
printf("%c", 'a' + (p[i] - 'a' + letterKey) % 26); | |
j++; | |
} | |
else | |
{ | |
// return unchanged | |
printf("%c", p[i]); | |
} | |
} | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Notes -