【问题标题】:Caesar cipher input text file凯撒密码输入文本文件
【发布时间】:2012-12-05 02:44:59
【问题描述】:

我正在尝试使用 C++ 创建凯撒密码。我将程序读入一个文本文件,但我需要它来加密文本并输出到屏幕。

这是我的加密代码,但我似乎无法让它工作。我才刚刚开始使用 C++,还不确定从哪里开始。

cout << "enter a value between 1-26 to encrypt the text: ";
cin >> shift;

while ((shift <1) || (shift >26)) {
    cout << "Enter a value between 1 and 26!: ";
    cin >> shift;
}

int size = strlen(text);
int i=0;

for(i=0; i<size; i++) {
    cipher[i] = (text[i]);
    if (islower(text[i])) {
        if (text[i] > 122) {
            cipher[i] = ( (int)(text[i] - 26) + shift);
        }
    } else if (isupper(text[i])) {
        if (text[i] > 90) {
            cipher[i] = ( (int)(text[i] - 26) + shift);
        }
    }
}

cipher[size] = '\0';
cout << cipher << endl;

【问题讨论】:

  • 您的缩进非常随意,使代码难以阅读。请修复这个问题,并让我们检查post a minimal, complete, compiling code
  • 欢迎来到 StackOverflow。 1) 修正缩进,2) 学习创建最小的、独立的示例,3) 研究 C++ 中的模运算符(%%=)。
  • 正如@Beta 所说,检查模运算符 (%),这是您的解决方案。
  • 如果他们只对字母字符进行凯撒移位,模数并没有多大帮助,或者至少它不是那么简单。

标签: c++ encryption


【解决方案1】:

首先,你的算法是错误的。

如果我们假设ASCII 输入,那么您需要加密介于 32(即空格)和 126(即波浪号 ~)之间的值,包括在内。为此,您可以将键(单个数字)添加到值中。如果结果大于 126(您的最高可用字符),您需要环绕并从 32 开始计数。这意味着 126 + 1 = 32、126 + 2 = 33 等。查找“模数”。

我建议您查找“调试”一词。一般来说,当你有一个算法时,你会尽可能地编写与算法匹配的代码。如果结果不是预期的,那么您使用调试器逐行逐行,直到您发现该行是您预期的结果并且您的代码的结果不再匹配。

【讨论】:

    【解决方案2】:

    重新格式化,制作可编译的广告固定算法(我认为试图实现的)

    #include <iostream>
    using namespace std;
    
    char text[] = {"This is my encryption code but I can't seem to get it to work. "
                   "I have only just started using C++ and not really sure where "
                   "to go from here."};
    char cipher[sizeof(text)];
    
    void main()
    {
        int shift;
        do {
            cout << "enter a value between 1-26 to encrypt the text: ";
            cin >> shift;
        } while ((shift <1) || (shift >26));
    
        int size = strlen(text);
        int i=0;
    
        for(i=0; i<size; i++)
        {
            cipher[i] = text[i];
            if (islower(cipher[i])) {
                cipher[i] = (cipher[i]-'a'+shift)%26+'a';
            }
            else if (isupper(cipher[i])) {
                cipher[i] = (cipher[i]-'A'+shift)%26+'A';
            }
        }
    
        cipher[size] = '\0';
        cout << cipher << endl;
    }
    

    【讨论】:

    • 哎呀,找到错误!应该完全重写它:-)
    • 自己修好了,不能放在那里。对于那些想要查看错误的人,请查看历史记录。
    • 非常感谢您的帮助,我明白我现在做错了什么,回复也很快。再次感谢。
    【解决方案3】:

    一些事情:

    1. 您正在检查字符 islower,然后检查是否 ascii 值为&gt; 122。这永远不会是真的。在默认 语言环境(标准 ascii),islower() 仅当 ascii 为 true 值在 [97, 122] (a-z) 范围内。这同样适用于 isupper()。它只对 65 到 65 之间的 ascii 值返回 true 90,包容。
    2. 无论如何,您已经在使用 ascii 值,因此 islower()isupper() 可能是多余的。这些等同于对范围进行边界检查,即text[i] &gt;= 97 &amp;&amp; text[i] &lt;= 122。它们是有用的快捷方式,但如果可以简化,请不要围绕它们编写代码。
    3. 如果值为

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      • 2014-03-07
      相关资源
      最近更新 更多