我有一个任务,我们要制作一个凯撒(腐烂)密码,但不使用数组表示法(a[b])。看起来它应该可以工作,但它会在字符串末尾发出随机垃圾,即使在第 41 行和第 51 行执行了检查
/* lab 08 */
/* exercise for loops and pointers */
/* assume that plain text which needs to be encrypted has
* only capital letters */
#include <stdio.h>
#include <stdlib.h>
int Caesar_encrypt(char *p, char *s, int enckey);
int Caesar_decrypt(char *p, char *s, int enckey);
int main(void){
char A[]="THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
char B[50], /* stores encrypted output string */
C[50]; /* stores decrypted output using string B as source */
int enckey,
statuse, statusd; /* they store return values from the functions */
printf("Plaintext for encryption is : %s \n", A);
printf("Input numerical key for Caesar's cypher : ");
scanf("%d", &enckey ); // COMPLETE THIS
putchar('\n');
printf("You entered encryption key %d \n", enckey);
/* encrypt by Caesar's cypher */
statuse= Caesar_encrypt(A, B, enckey);
printf("Ciphertext is : %s \n", B);
/* decrypt by Caesar's cypher */
statusd = Caesar_decrypt(B, C, enckey);
printf("Decrypted text is: %s \n", C);
exit (0);
}
int Caesar_encrypt(char *p, char *s, int enckey) { // COMPLETE THE INPUT PARAMETERS
enckey %= 26;
int i;
for (i = 0; *(p+i); i++) {
if (*(p+i) != ' ') *(s+i) = (*(p+i) - 'A' + enckey) % 26 + 'A';
else *(s+i) = ' ';
}
return 0;
}
int Caesar_decrypt(char *p, char *s, int enckey) { // COMPLETE THE INPUT PARAMETERS
enckey %= 26;
int i;
for (i = 0; *(p+i); i++) {
if (*(p+i) != ' ') *(s+i) = (*(p+i) - 'A' + 26 - enckey) % 26 + 'A';
else *(s+i) = ' ';
}
return 0;
}
样本输出:
Plaintext for encryption is : THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Input numerical key for Caesar's cypher : 1
You entered encryption key 1
Ciphertext is : UIF RVJDL CSPXO GPY KVNQT PWFS UIF MBAZ EPH8???THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Decrypted text is: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG47;Q9=@SGD PTHBJ AQNVM ENW ITLOR NUDQ SGD KZYX CNF8???THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG