Strange incorrect char encryption (ascii)

This is simple code, but I can not understand the strange event. The 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 gets the line entered here: It works .
In this case, it works with the key 5. 'y', changed to 'd' correctly.

But in this case: Does not work .
With the key from 7, it changes "y" to "Ç" instead of the correct "f", therefore, apparently, it does not execute the line: "text [i] = text [i] - 26;"

+4
source share
3 answers

, . , key :

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;
}
+2

[i] = [i] + ;

7, text[i] - 'y', char (, char ), .

modulo . .

text[i]= (text[i] - 'a' + key) % 26 + 'a';
+4

, '%'.
StackOverflow "++ caesar cipher" .

:

new_letter = (old_letter - 'a'); // Set the range from 0 to 25.
new_letter = (new_letter + key) % 26; // 26 letters in the alphabet.
new_letter += 'a'; // Convert back to a letter.
+2

All Articles