I need a code review for Caesar cipher

Catfish3 (119)
I'm planning to add this to the Source Code section, especially because the Caesar cipher seems popular as a homework.

I tried to write high quality, bare C++11 code.

Now is the time to shoot it down. Be ruthless!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
///
/// @file
/// @author Julius Pettersson
/// @copyright MIT/Expat License.
/// @brief Caesar cipher implementation.
///
/// This program demonstrates proficient usage of C++11's features to implement the Caesar cipher.
/// It was written with Doxygen comments.
///
/// http://en.wikipedia.org/wiki/Caesar_cipher
/// http://en.cppreference.com/
/// http://www.doxygen.org/
///

#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstddef>
#include <fstream>
#include <iomanip>
#include <ios>
#include <iostream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <string>

///
/// @brief Encrypts letters in [`src_begin`, `src_end`) range with given `shift` and writes to `dest_begin`.
/// @param src_begin            source range beginning
/// @param src_end              source range end
/// @param dest_begin           destination range beginning
/// @param shift                desired shift of the alphabet
/// @throw std::domain_error    for absolute values of `shift` greater or equal to the alphabet's length
/// @return `OutputIterator` to the element past the last element written.
///
template <typename InputIterator, typename OutputIterator>
OutputIterator caesar_cipher(InputIterator src_begin, InputIterator src_end, OutputIterator dest_begin, int shift)
{
    const std::string ab = "abcdefghijklmnopqrstuvwxyz"; // AlphaBet
    std::string rot_ab(ab); // ROTated AlphaBet

    if (static_cast<std::size_t> (std::abs(shift)) >= ab.length())
        throw std::domain_error("`shift' is not within required bounds.");

    if (shift < 0)
        std::rotate(rot_ab.rbegin(), rot_ab.rbegin() - shift, rot_ab.rend());
    else
        std::rotate(rot_ab.begin(), rot_ab.begin() + shift, rot_ab.end());

    return std::transform(src_begin, src_end, dest_begin, [ab, rot_ab](char c) -> char {
        if (std::isalpha(c))
        {
            if (std::isupper(c))
                return std::toupper(rot_ab.at(ab.find(std::tolower(c))));

            return rot_ab.at(ab.find(c));
        }

        return c;
    });
}

///
/// @brief Prints usage information and a custom message.
/// @param s    custom message to be printed
///
void print_usage(const std::string &s = "")
{
    std::cerr << "Usage example:\n";
    std::cerr << "\tprogram.exe input_file output_file shift\n\n";
    std::cerr << "Where `input_file' and `output_file' are distinct files,\n";
    std::cerr << "and `shift' is a signed integer ranging from -25 to 25\n";

    if (!s.empty())
        std::cerr << "\nERROR: " << s << '\n';

    std::cerr << std::endl;
}

#ifdef DEBUGGING

#include <cassert>
#include <cstring>

///
/// @brief Debugging program entry point.
///
int main()
{
    std::string s = "Wkh Txlfn Eurzq Ira Mxpsv Ryhu Wkh Odcb Grj";

    caesar_cipher(s.begin(), s.end(), s.begin(), -3);
    std::cout << s << std::endl;
    assert(s == "The Quick Brown Fox Jumps Over The Lazy Dog");

    char ca[] = "Exxego ex srgi!";

    caesar_cipher(ca, ca + std::strlen(ca), ca, -4);
    std::cout << ca << std::endl;
    assert(std::strcmp(ca, "Attack at once!") == 0);
}

#else

///
/// @brief Actual program entry point.
/// @param argc             number of command line arguments
/// @param [in] argv        array of command line arguments
/// @retval EXIT_FAILURE    for failed operation
/// @retval EXIT_SUCCESS    for successful operation
///
int main(int argc, char *argv[])
{
    if (argc != 4)
    {
        print_usage("Wrong number of arguments.");
        return EXIT_FAILURE;
    }

    std::ifstream input_file(argv[1], std::ios_base::binary);

    if (!input_file.is_open())
    {
        print_usage(std::string("input_file `") + argv[1] + "' could not be opened.");
        return EXIT_FAILURE;
    }

    std::ofstream output_file(argv[2], std::ios_base::binary);

    if (!output_file.is_open())
    {
        print_usage(std::string("output_file `") + argv[2] + "' could not be opened.");
        return EXIT_FAILURE;
    }

    int shift;

    if (!(std::istringstream(argv[3]) >> shift))
    {
        print_usage("`shift' conversion error.");
        return EXIT_FAILURE;
    }

    try
    {
        input_file.exceptions(std::ios_base::badbit | std::ios_base::failbit);
        output_file.exceptions(std::ios_base::badbit | std::ios_base::failbit);

        std::istreambuf_iterator<char> src_begin(input_file);
        std::istreambuf_iterator<char> src_end;
        std::ostreambuf_iterator<char> dest_begin(output_file);

        caesar_cipher(src_begin, src_end, dest_begin, shift);
    }
    catch (const std::ios_base::failure &f)
    {
        print_usage(std::string("File input/output failure: ") + f.what() + '.');
        return EXIT_FAILURE;
    }
    catch (const std::domain_error &de)
    {
        print_usage(de.what());
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

#endif 
Registered users can post here. Sign in or register to post.