C++ 中的凯撒密码编码:字符不会循环回 'a' 或 'A'
Caesar cipher encoding in C++: chars won't loop back to 'a' or 'A'
我正在编写一个 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
做出 "loop-over" 决定。
我怀疑您想先从 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] ++;
}
}
我正在编写一个 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
做出 "loop-over" 决定。
我怀疑您想先从 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] ++;
}
}