Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Osman Zakir
- // 10 13 2016
- // Introduction to Computer Science
- // Problem Set 2, caesar.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>
- #include <math.h>
- int main(int argc, string argv[])
- {
- if (argc == 1 || argc > 2)
- {
- printf("Error: Please input one number to use as key for cipher!\n");
- return 1;
- }
- printf("Enter plaintext to be shifted by %d positions\n", atoi(argv[1]));
- string plaintext = GetString();
- int key = atoi(argv[1]);
- const int size = strlen(plaintext);
- char ciphertext[size];
- if (key >= pow(2, 31) - 26 || key <= 0)
- {
- printf("The value for the key is invalid!\n");
- }
- else
- {
- for (int i = 0, n = size; i < n; i++)
- {
- if (isalpha(plaintext[i]))
- {
- //int c = plaintext[i] + key;
- ciphertext[i] = plaintext[i] + key;
- if (plaintext[i] >= 'Z' && isupper(plaintext[i]))
- {
- ciphertext[i] = ((plaintext[i] + key) - 'A') % 26;
- }
- else if (plaintext[i] >= 'z' && islower(plaintext[i]))
- {
- ciphertext[i] = ((plaintext[i] + key) + 'a') % 26;
- }
- /*if (plaintext[i] >= 'z')
- {
- ciphertext[i] = 'a' + (c % ('a' + 26));
- }
- else if (plaintext[i] >= 'Z')
- {
- ciphertext[i] = 'A' + (c % ('A' + 26));
- }*/
- }
- else
- {
- ciphertext[i] = plaintext[i];
- }
- }
- }
- printf("%s\n", ciphertext);
- return 0;
- }
Add Comment
Please, Sign In to add comment