fork(1) download
  1. #include <algorithm>
  2. #include <cctype>
  3. #include <string>
  4. #include <iostream>
  5.  
  6. template <typename InputIterator, typename OutputIterator>
  7. OutputIterator caesar_cipher(InputIterator src_begin, InputIterator src_end, OutputIterator dest_begin, int shift)
  8. {
  9. const std::string ab("abcdefghijklmnopqrstuvwxyz"); // AlphaBet
  10. std::string rot_ab(ab); // ROTated AlphaBet
  11.  
  12. shift %= static_cast<int> (ab.length()); // bring the shift within the length of the alphabet
  13.  
  14. if (shift < 0)
  15. std::rotate(rot_ab.rbegin(), rot_ab.rbegin() - shift, rot_ab.rend());
  16. else
  17. std::rotate(rot_ab.begin(), rot_ab.begin() + shift, rot_ab.end());
  18.  
  19. auto rotator = [ab, rot_ab](char c) -> char {
  20. if (std::isalpha(c))
  21. {
  22. if (std::isupper(c))
  23. return std::toupper(rot_ab.at(ab.find(std::tolower(c))));
  24.  
  25. return rot_ab.at(ab.find(c));
  26. }
  27.  
  28. return c;
  29. };
  30.  
  31. return std::transform(src_begin, src_end, dest_begin, rotator);
  32. }
  33.  
  34. int main() {
  35. std::string s = "Wkh Txlfn Eurzq Ira Mxpsv Ryhu Wkh Odcb Grj";
  36.  
  37. caesar_cipher(s.begin(), s.end(), s.begin(), -3);
  38. std::cout << s << std::endl;
  39. }
Success #stdin #stdout 0s 3064KB
stdin
Standard input is empty
stdout
The Quick Brown Fox Jumps Over The Lazy Dog