gpt4 book ai didi

c - 即使 char 数组以 null 终止并经过检查, printf 也会吐出垃圾

转载 作者:行者123 更新时间:2023-11-30 18:20:25 25 4
gpt4 key购买 nike

我有一个作业,我们要制作一个凯撒(rot)密码,但不使用数组符号(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

最佳答案

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

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

关于c - 即使 char 数组以 null 终止并经过检查, printf 也会吐出垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22486625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com