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;"
text[i]=text[i] + key;
When key is 7 and text[i]
is 'y'
addition result doesn't fit in char
(seems your char is signed) and result is implementation defined.
You are better of using a modulo operator in the addition. e.g.
text[i]= (text[i] - 'a' + key) % 26 + 'a';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With