Marco Rossi Marco Rossi - 1 month ago 16
C++ Question

strange wrong char's encryption (ascii)

It's a simple code but I can't understand a strange event.
Code:

void Crittografia::CifraTesto(char text[]){
int i;
for (i=0;i<strlen(text);i++){
text[i]=text[i] + key;
if(text[i] > 'z'){
text[i]=text[i] - 26;
}
}
}


The function receives the string entered here:
It works.

In this case it works with a key of 5. 'y' changed in 'd' correctly.

But in this case: Doesn't work.

With a key of 7 it changes 'y' in 'Ç' instead of the correct 'f', so apparently doesn't execute the row: "text[i]=text[i] - 26;"

Answer Source

As Giorgi said, your problem is with overflow. You can avoid it by subtracting key from both sides of the inequality:

for (int i=0; text[i]; i++) {
    if (text[i] > 'z' - key) // check whether (text[i] + key) would be past `z`
        text[i] -= 26 - key;
    else
        text[i] += key;
}