我正在编写一个 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/