Applying arrays to encode a string

I have to modify the “encode the line” part of the following code to use a repeating sequence of numbers to scramble the letters, instead of +1 for each letter.

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{
// encode string s by adding 1 to the ASCII code of each character
ifstream fin;
string fileName;
string line;
cout << "What file do you want to use for input? ";
getline(cin, fileName);
fin.open(fileName.c_str());

getline(fin, line);

for (int i = 0; i < line.length(); i++) //for each char in the string...
{
line[i]++; // bump the ASCII code by 1
}
ofstream fout;
fout.open("secret.txt", ios::app);
if (!fout.good()) throw "I/O error";
fout << line << endl;
fout << endl;
fin.close();
cout << line << endl;
}



I need to use this array and loop repeat the sequence -5, +8, +12, +6, +1, over and over.

const int SIZE = 5;
int offset[SIZE] = {-5, 8, 12, 6, 1};

int counter = 0;
while (true)
{
//cycle through the array
int index = counter % SIZE;
cout << offset[index] << endl;

// continue cycing?
char keepGoing;
cout << "Keep going? [Y/N]: ";
cin >> keepGoing;
cin.ignore(1000, 10);
if (keepGoing == 'n' || keepGoing == 'N') break;

// count how many loop cycles
counter++;

So I need to use this encryption scheme that would subtract 5 from the first letter in a line read for a file, then add 8 to the 2nd letter, then add 12 to the 3rd, 6 to the 4th, and 1 to the 5th. At the 6th letter, it would subtract 5 and continue repeating the sequence for any remaining letters in the line.

My first question is what does int index = counter % SIZE mean? Any help would be appreciated.
% is the modulo operator. It returns the remainder in a division between integers.
9 / 4 == 2

9 % 4 == 1

It's commonly used to make a value wrap around a certain range. 9 % 4 can only return 0, 1, 2, 3. When the remainder is 4, it means the result of the division is actually one higher and the remainder is 0.

Taking the modulo of a number with the size of an array yields a value that is always 0 <= value <= size-1.
This will ensure that, no matter how many times the loop restarts, you will never index outside the array.


In general given
result = min + (value % max)
then
min <= result < min+max
Last edited on
Topic archived. No new replies allowed.