【发布时间】:2022-01-14 19:33:33
【问题描述】:
我正在制作一个基本上“加密”文本的程序,方法是用其他字母替换字母。所以你基本上运行程序并输入一个分布,然后输入你想要加密的文本,它会给你返回密码。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <cs50.h>
#include <ctype.h>
string make_lower(string word);
int main (int argc, string argv[])
{
//we examine the input
if (argc < 2 || argc > 2)
{
printf("Usage: ./substitution key\n");
return (1);
}
if (strlen(argv[1]) != 26)
{
printf("Key must contain 26 characters.\n");
return (1);
}
if (strlen(argv[1]) == 26)
{
for (int i = 0; i < 26; i++)
{
if (isdigit(argv[1][i]))
{
printf("Key must onlyontain alphabetic characters.\n");
return (1);
exit(0);
}
}
for (int i = 0; i < 26; i++)
{
for (int o = i + 1; o < 26; o++)
{
if (argv[1][i] == argv[1][o])
{
printf("Key must not contain repeated characters.\n");
return (1);
exit(0);
}
}
}
//we prompt the user for the words to transcribe
const string text = get_string("plaintext: ");
//we set everithing in lower caso to compare it, and set a new variable to store the original text so we can convert the
// upper cases back later
string ntext = text;
printf("%s\n", text);
argv[1] = make_lower(argv[1]);
ntext = make_lower(ntext);
printf("%s\n", text);
string alphabet = "abcdefghijklmnopqrstuvwxyz";
//we substitute the text to the desired outcome
for (int i = 0, n = strlen(ntext); i < n; i++)
{
for (int o = 0; o < 26; o++)
{
if (ntext[i] == alphabet[o])
{
ntext[i] = argv[1][o];
}
}
}
printf("%s\n", text);
printf("ciphertext: ");
for (int i = 0, n = strlen(ntext); i < n; i++)
{
if (isupper(text[i]))
{
printf("%c", toupper(ntext[i]));
}
else
{
printf("%c", ntext[i]);
}
}
printf("%s\n", text);
printf("\n");
return(0);
exit(0);
}
}
string make_lower(string word)
{
for (int i = 0; i < strlen(word); i++)
{
word[i] = tolower(word[i]);
}
return(word);
}
所以我的问题出在代码的输出上,因为问题是如果你想要加密的文本是“Hello”,它应该出现像“Ktlly”这样的例子,但我的输出是“ktlly ",因此结果中不会显示大写字母。
当您输入要加密的代码时,程序将其存储在一个常量字符串中,然后创建一个新变量并将其设置为等于您输入的文本,然后程序将该新变量转换为小写,以便它可以进行比较,最后,当我们将文本加密时,我尝试通过创建一个 if 语句(在第 82 行)将那些我想要的字符再次变为大写,但事实并非如此。我试图看看为什么,这就是为什么我设置在第 56、62、78 和 94 行打印常量,看看为什么它不起作用,结果发现变量正在改变,即使应该是成为一个常数。起初在第 56 行,它仍然是原始文本;然后在第 62 行,它的文本相同,但小写;然后在第 78 行和第 94 行,它本身被修改为文本的加密版本。
基本上就是这样,我不知道为什么会这样。至少对我来说,代码似乎是正确的,我的理论是它与函数有关,或者与内置漏洞代码的大“if”语句有关。感谢您通读所有这些。
【问题讨论】: