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 <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <ctype.h> | |
#include <cs50.h> | |
// plaintext (p) vs ciphertex (c), and a key (k) | |
// “rotate” each (alphabetical) character by k positions | |
// Your program must accept a single command-line argument, a non-negative integer | |
// Your program must preserve case | |
// lowercase: 65(a) - 90(z) | |
// uppercase: 97(a) - 122(z) | |
// isalpha, islower, isupper, isdigit | |
int main(int argc, string argv[]) | |
{ | |
if (argc == 2) | |
{ | |
for (int i = 0; i < strlen(argv[1]); i++) | |
{ | |
if (isdigit(argv[1][i]) == 0) | |
{ | |
printf("Usage: ./caesar k\n"); | |
return 1; | |
} | |
} | |
int k = atoi(argv[1]); | |
string p = get_string("plaintext: "); | |
printf("ciphertext: "); | |
for (int i = 0, len = strlen(p); i < len; i++) | |
{ | |
if (islower(p[i])) | |
{ | |
printf("%c", (((p[i] - 'a') + k) % 26) + 'a'); | |
} | |
else if (isupper(p[i])) | |
{ | |
printf("%c", (((p[i] - 'A') + k) % 26) + 'A'); | |
} | |
else | |
{ | |
printf("%c", p[i]); | |
} | |
} | |
printf("\n"); | |
return 0; | |
} | |
else | |
{ | |
printf("Usage: ./caesar k\n"); | |
return 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment