I've implemented a Caesar cipher in C++ and would like for you to review it. It works as expected, at least with the inputs I've tried.
Feel free to suggest improvements, warn about bad practices or mistakes that I might be doing or give general tips.
// Caesar Cipher implementation
#include <iostream>
#include <string>
#include <algorithm>
#include <fstream>
#include <vector>
#include <cassert>
#include <iterator>
std::string encodeStr(const std::string& str, int shift, bool decodeFlag = false)
{
std::string str_enc;
// not sure if this function is doing to much
std::transform(str.cbegin(), str.cend(), std::back_inserter(str_enc), [&](char ch) -> char
{
if (ch == 'z' || ch == 'Z')
{
return ch - 25;
}
else if (isspace(ch))
{
return ' ';
}
else
{
if (islower(ch))
ch ^= 0x20; // XOR 6th bit don't care if it's lower case.
if (decodeFlag)
{
return ((ch - 'A' + 26) - shift) % 26 + 'A';
}
else
{
return ((ch - 'A') + shift) % 26 + 'A';
}
}
});
return str_enc;
}
std::vector<std::string> encodeVec(const std::vector<std::string>& strVector, int shift, bool decodeFlag = false)
{
std::vector<std::string> tempMsg;
tempMsg.reserve(strVector.size());
std::transform(strVector.cbegin(), strVector.cend(), std::back_inserter(tempMsg),
[&](const std::string& s) { return encodeStr(s, shift, decodeFlag); });
return tempMsg;
}
int main(int argc, char *argv[])
{
int choice;
std::cout << "What do you want to do? 1.Encrypt, 2.Decrypt: ";
std::cin >> choice;
if (!(choice == 1 || choice == 2)) {
return EXIT_FAILURE;
}
int key;
std::cout << "Enter desired shift: ";
std::cin >> key;
std::ifstream inFile("test.txt"); // Might ask for the file instead of hard coding it...
if (!inFile)
{
std::cout << "There was a problem with the file!";
return EXIT_FAILURE;
}
std::string line;
std::vector<std::string> lines;
while (std::getline(inFile, line))
{
lines.push_back(line);
}
const std::vector<std::string> finalResult = [&]()
{
return choice == 1 ? encodeVec(lines, key) : encodeVec(lines, key, true);
}();
std::ofstream outFile("test.txt");
std::copy(finalResult.cbegin(), finalResult.cend(),
std::ostream_iterator<std::string>(outFile, "\n"));
return EXIT_SUCCESS;
}