Created
May 26, 2023 10:55
-
-
Save andrija-zikovic/bb5a6ea7bfcf0b7232c89e66365cf4b6 to your computer and use it in GitHub Desktop.
CS50/caesar
This file contains 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 <ctype.h> | |
#include <string.h> | |
#include <stdlib.h> | |
int only_digits(string text); | |
int rotate(char c, int n); | |
int main(int argc, string argv[]) | |
// Make sure program was run with just one command-line argument | |
// Make sure every character in argv[1] is a digit | |
// Convert argv[1] from a `string` to an `int` | |
// Prompt user for plaintext | |
// For each character in the plaintext: | |
// Rotate the character if it's a letter | |
{ | |
if (argc != 2) | |
{ | |
printf("Usage: ./caesar key\n"); | |
return 1; | |
} | |
else if (!only_digits(argv[1])) | |
{ | |
printf("Usage: ./caesar key\n"); | |
return 1; | |
} | |
int k = atoi(argv[1]); | |
string plaintext = get_string("Plaintext: "); | |
printf("Ciphertext: "); | |
for (int j = 0; plaintext[j]!='\0'; ++j) | |
{ | |
printf("%c", rotate(plaintext[j], k)); | |
} | |
printf("\n"); | |
} | |
int only_digits(string text) | |
{ | |
for (int i = 0; text[i]!='\0'; ++i) | |
{ | |
if (!isdigit(text[i])) | |
{ | |
return 0; | |
} | |
} | |
return 1; | |
} | |
int rotate(char c, int n) | |
{ | |
if (isalpha(c)) | |
{ | |
if (isupper(c)) | |
{ | |
char new_c = (c - 65 + n) % 26 + 65; | |
return new_c; | |
} | |
else | |
{ | |
char new_c = (c - 97 + n) % 26 + 97; | |
return new_c; | |
} | |
} | |
else | |
{ | |
return c; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment