【问题标题】:Caesar cipher encoding in C++: chars won't loop back to 'a' or 'A'C++ 中的凯撒密码编码:字符不会循环回“a”或“A”
【发布时间】:2017-04-07 16:56:13
【问题描述】:

我正在编写一个凯撒密码,它从 .txt 读取明文,加密明文并写入第二个 .txt,然后读取第二个 .txt 并将其解密为第三个 .txt。除了对字母表末尾附近的字符进行加密外,一切正常。当一个字符到达'z'或'Z'时,它应该循环回到'a'或'A'。下面是我的编码函数中的一个 sn-p 代码,这是唯一导致问题的位。

if (isalpha(inputString[i])) {         //use isalpha() to ignore other characters
    for (int k = 0; k < key; k++) {     //key is calculated in another function, 6 in this case
        if (inputString[i] == 'z')      //these statements don't seem to work
            encryptedString[i] = 'a';
        else if (inputString[i] == 'Z')
            encryptedString[i] = 'A';
        else                            //this part works correctly
            encryptedString[i] ++;
    }               
}

输入:

快速的棕色狐狸

跳过----

房子或月亮什么的。

预期输出:

ZNK waoiq hxuct lud

Pasvkj ubkx znk----

Nuayk ux suut ux yusk-znotm。

实际输出:

Q{ick bro}n fo~

J{mped o|er the----

Ho{se or moon or something.

键:6

【问题讨论】:

  • 欢迎来到 Stack Overflow!听起来您可能需要学习如何使用调试器来逐步执行代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。延伸阅读:How to debug small programs
  • 您的代码中可能存在错误。如果你给我们看,我们也许能找到它。 IOW,请提供minimal reproducible example
  • 如果我没记错的话,凯撒密码只是简单地添加密钥并取模字母表中的字母数。所以你可以做ciphered[i] = (input[i] + key) % ('z' - 'a') + 'a'
  • @ZivS 你还需要一个“偏移量”,+'a'。否则它将不是有效的 ascii。
  • @Jonas,是的,刚刚修好了……

标签: c++ caesar-cipher


【解决方案1】:

您正在修改encryptedString,然后根据inputString 做出“循环”决定。

我怀疑你想首先从inputString 初始化encryptedString,然后只在encryptedString 上工作。 在我看来,你应该这样做:

encryptedString[i] = inputString[i]; // initialize encryptedString
if (isalpha(inputString[i]))
{
    for (int k = 0; k < key; k++)
    {
        if (encryptedString[i] == 'z') // read from encryptedString instead of inputString
            encryptedString[i] = 'a';
        else if (encryptedString[i] == 'Z') // read from encryptedString instead of inputString
            encryptedString[i] = 'A';
        else
            encryptedString[i] ++;
    }               
}

【讨论】:

  • 从输入更改为加密字符串修复了它。我确实在代码的前面设置了 encryptedString = inputString(就在我从 txt 文件中提取该行之后)。
猜你喜欢
  • 2018-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多