Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Osman Zakir
- // 10 15 2016
- // Introduction to Computer Science
- // Problem Set 2, vigenere.c
- // Take the key for the cipher from the user as a command-line argument and use it to encrypt a message
- #include <cs50.h>
- #include <stdio.h>
- #include <string.h>
- #include <ctype.h>
- #include <stdlib.h>
- bool isletterstring(string key);
- int main(int argc, string argv[])
- {
- if (argc == 1 || argc > 2)
- {
- printf("Usage: ./vigenere <key>\n");
- return 1;
- }
- string plaintext = GetString();
- string key = argv[1];
- const int key_size = strlen(key);
- const int plaintext_size = strlen(plaintext);
- char ciphertext[plaintext_size];
- if (isletterstring(key))
- {
- for (int i = 0, j = 0; i < plaintext_size; i++)
- {
- if (j >= key_size)
- {
- j = 0;
- }
- if (isalpha(plaintext[i]))
- {
- int k = toupper(key[j]) % 65;
- int c = plaintext[i] + k;
- if (toupper(c) > 'A')
- {
- c -= 26;
- }
- ciphertext[i] = c;
- j++;
- }
- else
- {
- ciphertext[i] = plaintext[i];
- }
- }
- printf("%s\n", ciphertext);
- }
- else
- {
- printf("Keyword must only contain letters A-Z and a-z\n");
- return 1;
- }
- return 0;
- }
- bool isletterstring(string key)
- {
- for (int i = 0, n = strlen(key); i < n; i++)
- {
- if (!isalpha(key[i]))
- {
- return false;
- }
- }
- return true;
- }
Add Comment
Please, Sign In to add comment