/****************************************************************************** * This filter program encrypts/decrypts text using a Caesar Cipher. * Input text is taken from standard input and output text is written * to standard output. Assume only ASCII input/output. * * The first command line argument is the shift amount [0-25] * The second command line argument is the encrypt "e" or decrypt "d" * mode. * * Copyright © 2017 Richard Lesh. All rights reserved. *****************************************************************************/ #undef NDEBUG #include "Utils.hpp" #include #include #include #include using namespace Utils; using namespace std; static string const UPPER_ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; static string const LOWER_ALPHA = "abcdefghijklmnopqrstuvwxyz"; static int const ALPHABET_LEN = UPPER_ALPHA.length(); int main(int argc, char **argv) { if (argc != 3) { cout << fmt::format("Syntax: {0:s} 0-{1:d} e|d", argv[0], ALPHABET_LEN - 1) << endl; exit(1); } int const SHIFT = Utils::stoiWithDefault(string(argv[1]), 0); bool const ENCRYPT = string(argv[2]) == "e"; int cp; while ((cp = getchar()) != EOF) { string alphabet; if (islower(cp)) { alphabet = LOWER_ALPHA; } else { alphabet = UPPER_ALPHA; } char result = char(cp); int pos = alphabet.find(result); if (pos >= 0) { if (ENCRYPT) { pos = (pos + SHIFT) % ALPHABET_LEN; } else { pos = (pos - SHIFT + ALPHABET_LEN) % ALPHABET_LEN; } result = alphabet[pos]; } putchar(result); } return 0; }