#include <stdio.h>
#include <string.h>
int main()
{
char greeting[]="\nHello World!\n";
int a;
for(int i=0; i<strlen(greeting); i++)
greeting[i]^=111;
for(int i=0; i<strlen(greeting); i++)
greeting[i]^=111;
printf("%s\n",greeting);
scanf("%d",&a);
}
Output:
Hell
Why does it cut everything after spotting a letter corresponding to the XOR key's number (in this case, ASCII 'w')? In mathematical logic, N^N=0
and 0^N=N
, doesn't it?
Because 'o'
is ASCII code 111, and XORing 111 with 111 yields 0, NUL
, and terminates your string. Once this happens (even in the first loop, since you're evaluating it each time through the loop), strlen
reports the string is much shorter, and the loops stop.
Saving the string length before going through the XORs will save you from this.
This is because when you xor a number with itself, it becomes zero, and when strlen sees zero, it thinks it's the end of the string.
If you store the length in a variable before the first loop and then use that saved length in your second loop instead of strlen, your program will produce the expected result.
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