c++ - C++ : chars won't loop back to 'a' or 'A' 中的凯撒密码编码

标签 c++ caesar-cipher

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

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 或 moon 或其他东西。

键:6

最佳答案

您正在修改 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] ++;
    }               
}

关于c++ - C++ : chars won't loop back to 'a' or 'A' 中的凯撒密码编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283457/

相关文章:

c++ - 如何减少使用std::condition_variable时生产者获得锁而消费者无法获得锁的可能性?

c - 将每个字母移动多个位置后,如何按字母顺序将 z 换成 a,将 Z 换成 A?

c - 在 C Caesar Cipher 中使用 ASCII 解密具有未知 key 的打开的文本文件

java - 凯撒密码(频率列表)

c++ - 混合 monotuch 和 Obj-C 或 C++

c++ - 需要将 ifstream 输入文件转换为我可以循环和解密的格式

c++ - GCC 有内置的编译时断言吗?

c# - C# 或 C++ 中的音频处理

python - 接收和旋转字符的函数 - Caesar Cipher

java - 如何使用另一个字符串中的字符替换字符串中的字符(Caesar Cypher)(JAVA)