![](/img/trans.png)
[英]Why does my program end after I input a certain amount of letters to the array?
[英]Why does my program only change some of the letters
因此,我正在尝试制作ROT13解码器,这就是我到目前为止所拥有的。 虽然只有一些字母会改变,但我不确定为什么。 我是编程新手。 我只是想弄清楚如何读文件和写文件。 到目前为止,该部分仍然有效,但是是的,它不会更改原始文件中的所有字母,只是其中的一部分。 我真的很感谢任何反馈。
#include <iostream>
#include <fstream>
//the letters in the secretMessage file are "Lbh unir gb fgnl va funcr. Zl tenaqzbgure, fur fgnegrq jnyxvat svir zvyrf n qnl jura fur jnf 60. Fur’f 97 gbqnl naq jr qba’g xabj jurer gur uryy fur vf
//
//
//and this is what it outputs to the decodedMessage file "Lbh haie gb fgal ia fhace. Ml geaadmbghee, fhe fgaeged jalkiag fiie milef a dal jhea fhe jaf 60. Fhe’f 97 gbdal aad je dba’g kabj jheee ghe hell fhe if.
using namespace std;
int main(){
ofstream fout;
ifstream fin;
fin.open("secretMessage.txt");
fout.open("decodedMessage.txt");
char c = 0;
while (!fin.eof()){
c = fin.get();
if (c == 'a')c = 'n';
if (c == 'b')c = 'o';
if (c == 'c')c = 'p';
if (c == 'd')c = 'q';
if (c == 'e')c = 'r';
if (c == 'f')c = 's';
if (c == 'g')c = 't';
if (c == 'h')c = 'u';
if (c == 'i')c = 'v';
if (c == 'j')c = 'w';
if (c == 'k')c = 'x';
if (c == 'l')c = 'y';
if (c == 'm')c = 'z';
if (c == 'n')c = 'a';
if (c == 'o')c = 'b';
if (c == 'p')c = 'c';
if (c == 'q')c = 'd';
if (c == 'r')c = 'e';
if (c == 's')c = 'f';
if (c == 't')c = 'g';
if (c == 'u')c = 'h';
if (c == 'v')c = 'i';
if (c == 'w')c = 'j';
if (c == 'x')c = 'k';
if (c == 'y')c = 'l';
if (c == 'z')c = 'm';
if (c == 'A')c = 'N';
if (c == 'B')c = 'O';
if (c == 'C')c = 'P';
if (c == 'D')c = 'Q';
if (c == 'E')c = 'R';
if (c == 'F')c = 'S';
if (c == 'G')c = 'T';
if (c == 'H')c = 'U';
if (c == 'I')c = 'V';
if (c == 'J')c = 'W';
if (c == 'K')c = 'X';
if (c == 'L')c = 'Y';
if (c == 'M')c = 'Z';
if (c == 'N')c = 'A';
if (c == 'O')c = 'B';
if (c == 'P')c = 'C';
if (c == 'Q')c = 'D';
if (c == 'R')c = 'E';
if (c == 'S')c = 'F';
if (c == 'T')c = 'G';
if (c == 'U')c = 'H';
if (c == 'V')c = 'I';
if (c == 'W')c = 'J';
if (c == 'X')c = 'K';
if (c == 'Y')c = 'L';
if (c == 'Z')c = 'M';
cout << c;
if (!fin.eof())fout << c;
}
fin.close();
fout.close();
return 0;
}
您的示例中的大多数字母将被翻转两次。 您要么需要添加大量的“ else”命令,要么使用switch语句。
if (c == 'a')c = 'n';
else if (c == 'b')c = 'o';
有一种更好的数学方法。 但我会将其留给读者练习。
您有逻辑错误。 如果以“ a”开头,则第一个IF会将其转换为“ n”,随后的IF将其转换回为“ a”。
看一下switch
语句。
if
您有新行,则不应该使用if
条件的情况,因为每个条件都会被检查。 假设您的字符是l
那么您的if语句将字母更改为y
但是还检查了y
的条件,因此该字符更改回了l
。 因此,实际上您的代码并未更改某些字母,而是对其进行了两次更改。
对于后续的输入,您应该可以使用else if
来解决此问题,这样当一个为true时,其他输入就不会被检查,或者可以使用switch case
。
取一个用ROT13编码的字母。 如果对它进行两次编码,则会再次得到原始字母,这使得ROT13的编码和解码几乎相同。
现在以字母“ a”为例。 您上面在代码中所做的是
if (c == 'a') c = 'n';
...
if (c == 'n') c = 'a';
因此,对于上述字母的前半部分(a至m),您编码了两次,再次获得相同的字母。 仅对于字母的下半部分,编码仅执行一次。
一种解决方案是将您的语句更改为类似
if (c == 'a') { c = 'n'; continue; }
如果匹配,这将跳过其余代码,并continue
进行下一个循环迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.