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
| #include <iostream>
#include <algorithm>
#include <sstream>
#include <locale>
#include <array>
#include <string>
#include <cassert>
std::string encrypt(int shift, std::string word);
std::string decrypt(int shift, std::string word);
int main()
{
int shift = 5;
std::stringstream sentence("Hello World ABCDEFgHIJKLmNOPqRSTUVWXYZ");
std::stringstream encrypted_sentence;
std::stringstream decrypted_sentence;
while(!sentence.eof())
{
std::string temp;
sentence >> temp;
encrypted_sentence << encrypt(shift, temp) << " ";
}
while(!encrypted_sentence.eof())
{
std::string temp;
encrypted_sentence >> temp;
decrypted_sentence << decrypt(shift, temp) << " ";
}
std::cout << sentence.str() << std::endl;
std::cout << encrypted_sentence.str() << std::endl;
std::cout << decrypted_sentence.str() << std::endl;
}
std::string encrypt(int shift, std::string word)
{
static const std::array<char, 26> letters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
if(shift != 0)
{
for(std::string::iterator it = word.begin(); it != word.end(); ++it)
{
bool was_lower = false;
if(std::islower(*it))
{
was_lower = true;
*it = std::toupper(*it);
}
std::array<char, 26>::const_iterator new_character = std::find(letters.begin(), letters.end(), *it);
assert(new_character != letters.end());
if(shift > 0)
{
for(int i = 0; i < shift; ++i)
{
++new_character;
if(new_character == letters.end())
new_character = letters.begin();
}
}
else
{
for(int i = 0; i > shift; --i)
{
if(new_character == letters.begin())
new_character = letters.end();
--new_character;
}
}
if(was_lower)
*it = std::tolower(*new_character);
else
*it = *new_character;
}
}
return word;
}
std::string decrypt(int shift, std::string word)
{
return encrypt(-shift, word);
} |
Partager