-1

我有一个任务,我们要制作一个凯撒(腐烂)密码,但不使用数组表示法(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 
4

3 回答 3

3

您不会在加密或解密函数中对结果字符串进行零终止。

您需要在加密函数的循环之后和解密函数的循环之后添加*(p+i) = 0;或,最好是。 p[i] = 0;s[i] = 0;

于 2014-03-18T17:30:23.130 回答
2

我认为问题在于您的加密/解密函数在源数组中遇到零时会停止加密/解密(这是正确的),但它们没有明确地以零终止目标数组(这是一个问题)。尝试在循环之后添加显式空终止。

于 2014-03-18T17:29:16.123 回答
2

您需要正确终止您的Caesar_encrypt()Caesar_decrpyt()函数中的字符串。
C 字符串以单个'\0'字符return 0;结尾,因此您可以在上述函数体底部的之前添加这一行:

    .... 

    // Terminate the string, adding a \0
    *(s+i) = '\0';

    return 0;
}

顺便说一句:我更喜欢使用数组语法 s[i]来识别字符串中的单个字符,所以我会使用s[i] = 0;.


此外,您可能希望使用const在函数签名中标记输入(只读)字符串(以及更新函数定义):

int Caesar_encrypt(const char *p, char *s, int enckey);
int Caesar_decrypt(const char *p, char *s, int enckey);
于 2014-03-18T17:38:34.707 回答