凯撒密码输入文本文件

时间:2012-12-04 17:21:31

标签: c++ encryption

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

这是我的加密代码,但我似乎无法让它工作。我刚刚开始使用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;

3 个答案:

答案 0 :(得分:1)

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

如果我们假设ASCII输入,则需要加密32(即空间)和126(即波浪线〜)之间的值,包括端值。您可以通过将键(单个数字)添加到值来完成此操作。如果结果大于126(您的最高可用字符),则需要环绕并从32开始计数。这意味着126 + 1 = 32,126 + 2 = 33等。查找“模数”。

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

答案 1 :(得分:0)

一些事情:

  1. 您正在检查字符islower,然后检查是否 ascii值为> 122。这永远不会成真。在默认情况下 locale(标准ascii),islower()只有ascii才会生效 值在[97,122](a-z)范围内。同样的道理 isupper()。它仅对65和之间的ascii值返回true 90,包容性。
  2. 您无论如何都在使用ascii值,因此islower()isupper()可能是多余的。这些等同于对范围进行边界检查,即text[i] >= 97 && text[i] <= 122。它们是有用的快捷方式,但如果您可以简化,则不要以您的代码为基础。
  3. 如果值为&lt; = 90/122,您的代码永远不会添加凯撒班次,因此您永远不会转移任何东西。

答案 2 :(得分:0)

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

#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;
}