Ceasar cipher

So I this Ceaser cihper code that I wrote, but I would like it to only encrypt every fifth letter. So if I write, aaaaaaaaaaaaa it would become nnnnnaaaaannn.

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
#include <iostream>
#include <string>

using namespace std;
int main()
{
    string input;
    int cnt=0, length;
    
    cout << "Write something: ";
    getline(cin, input);
    
    length = (int)input.length();
    
    for( cnt=0; cnt < length; cnt++)
    {
        if(isalpha(input[cnt]))
        {
            input[cnt] = tolower(input[cnt]);
            for (int i=0; i< 13; i++)
            {
                if(input[cnt] == 'z')
                    input[cnt] = 'a';
                else
                    input[cnt]++;
            }
        }
            
    }
    
    cout << "Result: " << input << endl;
    
    return 0;
}
Use the modulo operation. See:

http://www.cplusplus.com/doc/tutorial/operators/

if((i % 5) == 0) // This means every 5th index (5, 10, 15, ...)

So if I write, aaaaaaaaaaaaa it would become nnnnnaaaaannn.
This is not ever 5th.

To achieve this you need to (integer) length /= 5. Use 2 nested loops. In the inner loop write 5 characters either encrypted or not depending on a bool variable e.g. is_encrypted. For the alternation you can use bool is_encrypted = !is_encrypted before the inner loop (initialize it properly before the outer loop of course).
I meant the second of your alternatives, what do you call that then if not every 5th?

Can you explain that further because I don't quite understand.
Every fifth element refers to elements with zero-based indices 5n for all nonnegative integers n.
You've described alternating groups of five.

I don't understand coder777's suggestion, but here's mine, not tested:
1
2
3
4
5
void rot13(char &c) { ... }
...
for (auto i = std::size_t{}; i < std::size(str); ++i) {
  if (! ((i / 5u) % 2)) rot13(str[i]); 
}
Last edited on
Topic archived. No new replies allowed.