问题
#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?
回答1:
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.
回答2:
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.
回答3:
greeting[5]
is 'o' which is 111 in ASCII.
Hence greeting[5] ^ 111 will be zero (which will terminate your string)
The strlen in the second loop will return a different value.
To fix this, use a variable len to store the original strlen. You will get your string back !!!
Modified:
#include <stdio.h>
#include <string.h>
int main()
{
char greeting[]="\nHello World!\n";
int a;
int len = strlen(greeting);
for(int i=0; i<len; i++)
greeting[i]^=111;
for(int i=0; i<len; i++)
greeting[i]^=111;
printf("%s\n",greeting);
scanf("%d",&a);
}
来源:https://stackoverflow.com/questions/10392204/xoring-hello-world-cuts-off-string