Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Vigenere cipher created for CS50 intro to CS course
- #include <cs50.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- int main(int argc, string argv[])
- {
- //Only accept one key word. No more no less.
- if (argc !=2)
- {
- printf("Gimmie ONE key\n");
- return 1;
- }
- //No numbers allowed in key word
- else
- {
- for (int i = 0, n = strlen(argv[1]); i < n; i++)
- {
- if (isdigit(argv[1][i]))
- {
- printf("No numbers! Geez!\n");
- return 1;
- }
- }
- }
- string k = argv[1];
- string p = get_string("Input plaintext: ");
- printf("ciphertext: ");
- for (int i = 0, j = 0, n = strlen(p), klength = strlen(k); i < n; i++)
- {
- //check if plaintext character is a letter
- if (isalpha(p[i]))
- {
- //check if plaintext character is lowercase
- if (islower(p[i]))
- {
- //Check if cipher character is lowercase and make a = 0, b = 1, etc if so.
- if (islower(k[j]))
- {
- printf("%c", (((p[i] + ((k[j] - 97) % 26) - 97) % 26) + 97));
- }
- //If cipher character is uppercase, make A = 0, B = 1, etc.
- else
- {
- printf("%c", (((p[i] + ((k[j] - 65) % 26) - 97) % 26) + 97));
- }
- }
- //Same as above but for uppercase plaintext character
- else
- {
- if (islower(k[j]))
- {
- printf("%c", (((p[i] + ((k[j] - 97) % 26) - 65) % 26) + 65));
- }
- else
- {
- printf("%c", (((p[i] + ((k[j] - 65) % 26) - 65) % 26) + 65));
- }
- }
- //loop through cipher key
- j = (j + 1) % klength;
- }
- //Simply print character if non-alpha
- else
- {
- printf("%c", p[i]);
- }
- }
- printf("\n");
- }
Add Comment
Please, Sign In to add comment