Please fix your spaces/tabs, it spoils your indentation when posted as tabs are expanded to 8 spaces.
As you copied my sample, error and all, I'll go over it in detail.
main()
, on encryption, reads each line of the
unencrypted
file into
line
. Each character in
line
is sent to
encrypt()
with a random number of suitable range.
encrypt()
looks up
c
's position in the map of input characters, then increments the position by
r
, the random number. Mod is used to handle any wrap that occurs.
How do we encode
encrypt()
?
First we need to find the position of
c
. STL has
find()
that we can use. We give a range and the object, and it returns where in the range it is, or not as the case might be.
1 2 3 4 5 6 7
|
// find the position of the char in the char map
const char* p = std::find(chmap, chmap + sizeof(chmap), c);
if (p == chmap + sizeof(chmap))
throw std::domain_error("Input character out of range");
// find the index of the char
ptrdiff_t idx = p - chmap;
|
Next, we apply the random interval by moving that position. We just move the pointer along with addition, then use the modulus to handle wrap.
1 2 3
|
// add on the random offset
idx += r;
idx = idx % sizeof(chmap);
|
Let me know if you don't (or do) understand this, then we can fix decryption.