fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <cctype>
  4. #include <algorithm>
  5.  
  6.  
  7. std::string caesar(std::string input, int shift)
  8. {
  9. static const std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
  10. static std::string cypher = alphabet;
  11. auto middle = (shift > 0 ? alphabet.begin() : alphabet.end()) + shift;
  12. std::rotate_copy(alphabet.begin(), middle, alphabet.end(), cypher.begin());
  13. std::transform(input.begin(), input.end(), input.begin(), [&cypher](char c)
  14. {
  15. std::string::size_type pos = alphabet.find(tolower(c));
  16. return (pos != std::string::npos ? cypher[pos] : c);
  17. });
  18. return input;
  19. }
  20.  
  21. int main()
  22. {
  23. std::string x = "Hello, world!";
  24. std::string y = caesar(x, 5);
  25. std::cout << y << '\n' << caesar(y, -5);
  26. }
  27.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
mjqqt, btwqi!
hello, world!