Created
July 16, 2020 15:11
-
-
Save aryan348/b94f1e82a4925409b611fe2652db79b9 to your computer and use it in GitHub Desktop.
CS50 Problem Set 2 (Fall 2020) - Caesar
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 <stdio.h> | |
#include <string.h> | |
#include <ctype.h> | |
#include <stdlib.h> | |
// function declaration | |
int encrypt(int k); | |
int main(int argc, string argv[]) | |
{ | |
int extra = 0; | |
int callEncrypt; | |
// argc command line should only accept one key | |
if (argc != 2 || argc > 2) | |
{ | |
printf("Usage: ./caesar key\n"); | |
return 1; | |
} | |
// check if onlly digit or there is some other char in command line | |
for (int i = 0, n = strlen(argv[1]); i < n; i++) | |
{ | |
// printf("%c", argv[1][i]); | |
if (isdigit(argv[1][i])) | |
{ | |
} | |
else | |
{ | |
extra++; | |
} | |
} | |
// if there is extra char other than digit throw error message | |
if (extra >= 1) | |
{ | |
printf("Usage: ./caesar key\n"); | |
return 1; | |
} | |
// else if convert argv command line to integer | |
else | |
{ | |
int key = atoi(argv[1]); | |
// call encrypt function | |
callEncrypt = encrypt(key); | |
return 0; | |
} | |
} | |
int encrypt(int k) | |
{ | |
string text; | |
int capitalAlphaIndex = 65; | |
int lowerAlphaIndex = 97; | |
do | |
{ | |
// prompting to get text | |
text = get_string("Plaintext: "); | |
} | |
// do while to not accept empty | |
while (text < 0); | |
printf("ciphertext: "); | |
// for loop for turning string to char | |
for (int i = 0, n = strlen(text); i < n; i++) | |
{ | |
if (isupper(text[i])) | |
{ | |
// if upper encrypts charachter by key but also encrypted text char is Upper | |
// converts to capital letters alphabet index by deducing 65 | |
text[i] = text[i] - capitalAlphaIndex; | |
// applying the formula for encrypt | |
text[i] = (text[i] + k) % 26; | |
// converts to capital letters back to ASCII so it doesn't ciphers to other ascii characters | |
// it ciphers only to alphabets | |
text[i] = text[i] + capitalAlphaIndex; | |
printf("%c", text[i]); | |
} | |
else if (islower(text[i])) | |
{ | |
// converts to lower letters alphabet index by deducing 97 | |
text[i] = text[i] - lowerAlphaIndex; | |
// applying the formula for encrypt | |
text[i] = (text[i] + k) % 26; | |
// converts to lower letters back to ASCII so it doesn't ciphers to other ascii characters | |
// it ciphers only to alphabets | |
text[i] = text[i] + lowerAlphaIndex; | |
printf("%c", text[i]); | |
} | |
else | |
{ | |
// print as it is if non alphabets | |
printf("%c", text[i]); | |
} | |
} | |
printf("\n"); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment