#include<stdio.h>
int main()
{
//ask the user what they want to encrypt or decrypt a string
printf("Do you want to encrypt or decrypt a string? (e/d): ");
char choice;
scanf("%c", &choice);
//if the user wants to encrypt, then use cipher.txt to encrypt the string
if (choice == 'e')
{
//ask the user for the string they want to encrypt
printf("Enter the string you want to encrypt: ");
char string[100];
scanf("%s", string);
//open cipher.txt
FILE* cipher;
cipher = fopen("cipher.txt", "r");
//read the cipher.txt file
char cipherText[26];
fscanf(cipher, "%s", cipherText);
//close cipher.txt
fclose(cipher);
//encrypt the string
int i;
for (i = 0; i < 100; i++)
{
if (string[i] == '\0')
{
break;
}
else if (string[i] >= 'a' && string[i] <= 'z')
{
string[i] = cipherText[string[i] - 'a'];
}
else if (string[i] >= 'A' && string[i] <= 'Z')
{
string[i] = cipherText[string[i] - 'A'] - 32;
}
}
//print the encrypted string
printf("The encrypted string is: %s: ", string);
}
//if the user chooses decryption, then decrypt the string
else if (choice == 'd')
{
//ask the user for the string they want to decrypt
printf("Enter the string you want to decrypt: ");
char string[100];
scanf("%s", string);
//open cipher.txt
FILE* cipher;
cipher = fopen("cipher.txt", "r");
//read the cipher.txt file
char cipherText[26];
fscanf(cipher, "%s", cipherText);
//close cipher.txt
fclose(cipher);
//decrypt the string
int i;
for (i = 0; i < 100; i++)
{
if (string[i] == '\0')
{
break;
}
else if (string[i] >= 'a' && string[i] <= 'z')
{
string[i] = cipherText[string[i] - 'a'];
}
else if (string[i] >= 'A' && string[i] <= 'Z')
{
string[i] = cipherText[string[i] - 'A'] - 32;
}
}
//print the decrypted string
printf("The decrypted string is: %s", string);
}
}
我试着打开并使用Cipher.txt文件来交换字母并加密像hello这样的简单单词,并且能够通过输入密码文本来解密它们。Cipher.txt文件的编写目的是交换字母:
H、X、E、P、L、R、O、Q
我不知道如何让我的程序读取该文件,并与给定文件交换字母
1条答案
按热度按时间osh3o9ms1#
code至少有这些问题。
代码可能会溢出
cipherText[]
。请改用比大小小1的宽度限制。关于
cipher.txt
的内容尚不清楚,但它似乎有25个字母Map[A-Z],但没有'O'。我希望cipher.txt包含26个大写字符:
QWRST...A
.cipher.txt文件可疑,因为它1)没有26个Map,2)将一些字母Map为非字母。
第二个问题是,如果原始消息包含非字母,则很难破译。
cipherText[]
太小**要使用
fscanf(cipher, "%s", cipherText);
从文本文件中读取密码并使用它对26个字母进行编码,cipherText[]
需要为27以保存26个字母的Map和 * null字符 *。OP表示密码具有大写Map。然后需要更改编码:
看起来像是使用相同的
"cipher.txt"
文件重复加密代码。代码需要反转Map,而不是简单地再次应用它。