As you can see in the code the first encrypter moves the letters 13 steps for the five first letters and the second moves the letters 7 steps for the next five letters. I would like to keep on going with that so letter 11-15 moves 13 steps, letter 16-20 moves 7 steps etc, without creating a endless code. How could I do that? Should I use a loop of some sort?
If I were you, the first thing I'd do is separate my character encryption logic into a separate function so that I don't have to think about it while trying to figure out how to switch the rotation every 5 characters. Have a function that takes a character and a rotation, then returns an encrypted character. Then, you can loop over the entire string and every 5 steps change the rotation parameter that's passed to the encrypt function.
#include <iostream>
#include <string>
#include <cctype>
// Takes the character argument ptChar (plaintext character) and rotates it
// by whatever is specified in rotAmount if ptChar is a letter of the alphabet
// If ptChar is not a letter of the alphabet, it returns ptChar as is.
char rotCipherEncrypt(char ptChar, unsignedshort rotAmount)
{
if(std::isalpha(ptChar))
{
ptChar = tolower(ptChar);
for (int i = 0; i < rotAmount; i++)
{
if(ptChar == 'z')
ptChar = 'a';
else
ptChar++;
}
}
return ptChar;
}
// program entry point
int main()
{
std::string plaintext;
std::cout << "Enter plaintext: ";
std::getline(std::cin, plaintext);
std::string cipherText = plaintext;
unsignedshort rotation = 13;
for(int i = 0; i < plaintext.size(); i++)
{
cipherText[i] = rotCipherEncrypt(plaintext[i], rotation);
// if the next character falls on the other side of a 5-char boundary
// we need to change the rotation we're using
if( (i + 1) % 5 == 0)
{
if(rotation == 13) rotation = 7;
else rotation = 13;
}
}
std::cout << plaintext << "\nencrypts to\n" << cipherText << std::endl;
return 0;
}
13 can be replaced by a variable, to indicate how many rotations can be done and input[cnt] can be replaced by the current character to rotate.
Like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void rotate_char( char& c, int amount )
{
if( isalpha( input[cnt] ) ) {
c = tolower( input[cnt] );
for( int i = 0; i < amount; i++ ) {
if( c == 'z' ) c = 'a';
else c++;
}
}
else {
cout << "invalid character!\n";
return;
}
}