66 lines
1.7 KiB
C
66 lines
1.7 KiB
C
#include <cs50.h>
|
|
#include <ctype.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
int main(int argc, string argv[])
|
|
{
|
|
// Make sure program was run with just one command-line argument
|
|
if (argc > 2 || argc < 2)
|
|
{
|
|
printf("Usage: ./caesar {key}\n");
|
|
return 1;
|
|
}
|
|
|
|
// Make sure every character in argv[1] is a digit
|
|
for (int i = 0; i < strlen(argv[1]); i++)
|
|
{
|
|
if (!isdigit(argv[1][i]))
|
|
{
|
|
printf("Usage: ./caesar {key}\n");
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
// Convert argv[1] from a `string` to an `int`
|
|
int key = atoi(argv[1]);
|
|
|
|
// Prompt user for plaintext
|
|
string plaintext = get_string("plaintext: ");
|
|
|
|
// For each character in the plaintext:
|
|
string ciphertext = plaintext;
|
|
for (int i = 0; i < strlen(plaintext); i++)
|
|
{
|
|
if (isalpha(plaintext[i]))
|
|
{
|
|
int n;
|
|
// Rotate the character if it's a letter
|
|
char plaintextChar = (char) plaintext[i];
|
|
if (isupper(plaintextChar))
|
|
{
|
|
n = 65;
|
|
}
|
|
else
|
|
{
|
|
n = 97;
|
|
}
|
|
int plainAlphaIndex = (int) plaintextChar - n;
|
|
int cipherAlphaIndex = (plainAlphaIndex + key) % 26;
|
|
char ciphertextChar = (char) cipherAlphaIndex + n;
|
|
// printf("pT = %c, pAI = %i, cAI = %i, cT = %c", plaintextChar, plainAlphaIndex,
|
|
// cipherAlphaIndex, ciphertextChar);
|
|
ciphertext[i] = ciphertextChar;
|
|
}
|
|
else
|
|
{
|
|
ciphertext[i] = plaintext[i];
|
|
}
|
|
// printf("\n");
|
|
}
|
|
printf("ciphertext: %s", ciphertext);
|
|
printf("\n\n");
|
|
return 0;
|
|
}
|