2
Some letters of the encryption are passing from 'z', and going to symbols in the ASCII table, why is this occurring?
#include <stdio.h> // CRIPTOGRAFIA ROT13
#include <stdlib.h> // A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
#include <string.h>
int main()
{
int i;
char Palavra[255];
printf ("Digite a palavra que deseja criptografar: ");
scanf (" %s", Palavra);
for (i = 0; i < strlen(Palavra); i++)
{
if (Palavra[i] >= 'a' && Palavra[i] <= 'z')
{
Palavra[i] = Palavra[i] + 13;
}
if (Palavra[i] > 'z')
{
Palavra[i] = Palavra[i] - 26;
}
}
printf ("%s\n", Palavra);
return 0;
}
For which input did you realize this happened and what was the output generated?
– Woss
By chance your input that presented error has uppercase letters?
– anonimo
@Max comparison between
char
exists and is considered the alphabetical order (actually it is compared the respective integer values, but the result is the same).– Woss
No, no uppercase letters... The input was: Gui // The output: t?v // https://imgur.com/vja1l5n @Andersoncarloswoss
– Gui
The way you did when adding 13 you can get a number outside the standard ASCII table (from 0 to 127) and, depending on the character set used, for example. ISO-8859-1 or even UTF-8, may represent an invalid value for character representation.
– anonimo
The character
'u'
is the value 117, b'01110101'; when you sum 13 you will get the value 130, b'10000010'. As you are doing mathematical operations, this value will be treated as an integer and, for the integer, the first bit represents the sign; that is, you do not get the value 130, but -126. This way when you check whether you passed from'z'
you are comparing if -126 is greater than 122; since it is not, the value -126 remains. It is not an ASCII character, so it is displayed the "?".– Woss
I’m pretty sure there’s some question/answer on the site treating this very thoroughly, so possibly it would be duplicate.
– Woss
Your problem has to do with the type actually. Once you used
char
instead ofunsigned char
, when sum13
in the'u'
that is117
gets-126
and not130
, and so if you have thenif (Palavra[i] > 'z')
is not executed as the value is lower-126 < 122
. Change the guy tounsigned char
your code is working– Isac