This is because you are just "going forward" - your code has no prediction to go back to the letter 'a'
after passing the 'z'
.
For the C language, characters and numbers between -128 and +127 are indistinct - all are the type "char" - but the code of 'z'
+ 23 is greater than +127 - so you can use unsigned char if you want to check on a if
only after the sum. Your code could look like this:
#define CHAVE 23
int main() {
char texto[7] = "barfoo";
unsigned char novo;
int tamanho = strlen(texto);
for(int i = 0; i < tamanho; i++) {
novo = texto[i] + CHAVE;
if (novo > 'z') {
novo -= 26;
}
printf("%c", novo);
}
printf("\n");
exit(0);
}
This code works for keys up to 26: when finding any character code that is beyond the lowercase 'z', it subtracts 26 back to the beginning of the alphabet, and counting from there. It’s still far from ideal that would work for upper and lower case characters as well as other symbols.
Notice some other suggestions - for example, separating the value from chve to a point in the file where it is more readable, and easy to change.
As a final note - bear in mind that this type of experience is very cool for programming learning, and even for personal fun and friends - but as serious encryption it does not work. This type of encoding is known as the "Cezar cipher" - and for centuries it has been widely used - but with the formal advances of cryptography in the last century, it has only become a toy, and any professional in the field can discover the key in a few minutes (or less)after only striking eye at the ciphertext in this way.
Do you want only letters? or numbers and signs too?
– Anderson Henrique
Hello Anderson, just the letters, in the complete file I already made a function to skip the special characters and the numbers
– José Isaac
So, why aren’t you skipping the special characters. The } is right
– Anderson Henrique
Thank you Anderson
– José Isaac