gpt4 book ai didi

c - 我的解密器不工作

转载 作者:太空宇宙 更新时间:2023-11-04 08:14:18 24 4
gpt4 key购买 nike

我为 pset2 创建了两个东西,一个凯撒密码加密器和解密器。我的加密器可以工作,它叫做 caesar.c,但我的解密器 (decryptor.c) 不工作,我不明白为什么?这是我的代码。

凯撒.c

#include <cs50.h> 
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "encryptorFunction.c"


int main(int argc, string argv[]) {
//checks for enough args
if (argc >= 2) {
//converts the second arg to an integer
int k = atoi(argv[1]);
string stringToBeEncrypted = GetString();
printf("%s\n", encryptor(stringToBeEncrypted, k));
} else {
printf("Please add a key argument\n");
return 1;
}
}

解密器.c

    #include <cs50.h> 
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include "encryptorFunction.c"

// almost same as caesar


int main(void) {
const string stringToBeEncrypted = GetString();
// string stringToBeEncrypted = GetString();
//checks all possible decryptions
for(int k=1;k<26;k++) {
printf("%s\n", encryptor(stringToBeEncrypted, k));
}
}

加密函数.c

    #include <cs50.h> 
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>

string encryptor(string encryptString, int key) {
//loops through every character
string encryptStringCopy = encryptString;
for (int i = 0, n = strlen(encryptStringCopy); i < n; i++) {
//converts the specific char to its ascii value
int ascii = (int) encryptStringCopy[i];
//makes key 31 is the same as key 5
key = key % 26;
//checks if it is an alphabetical letter
if (isalpha(encryptStringCopy[i])) {
//checks if lowercase
if (islower(encryptStringCopy[i])) {
//handles the corner case of being z since 26 % 26 is not 26 it's 0
if ((ascii-96+key) == 26) {
ascii = 122;
}else {
//takes the lowercase alphabetical numbers to the 1-26 alphabet then checks mod 26 to cycle back and adds it back.
ascii = ((ascii-96+key) % 26) + 96;
}
//else part is for uppercase case
}else {
//same logic as above
if ((ascii-64+key) == 26) {
ascii = 90;

}else {
ascii = ((ascii-64+key) % 26) + 64;
}
}
}
//converts the ascii back to a char
char newChar = (char) ascii;
//sets the new char into the string
encryptStringCopy[i] = newChar;
}
return encryptStringCopy;
}

最佳答案

您的 encryptor() 函数修改输入字符串(参数 encryptString)。因此,对同一输入重复调用它会产生意想不到的结果。

该函数应该创建一个新的字符串来返回,而不是修改传入的字符串。

关于c - 我的解密器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36679902/

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