我写了这份守则来写日记或日记。它接受输入,对其进行加密并将其存储在名为“ yourDiary.txt”的文件中。当要求解密时,它要求输入密码(当前为“ pwd”)。如果密码匹配,则将“ yourDiary.txt”解密为“ yourDiaryDecrypted.txt”。它通常工作正常。但是,如果在文本编辑器中打开“ yourDiary.txt”,则程序将进入无限循环,并且“ yourDiaryDecrypted.txt”将无限期增长。有人请告诉共振。
我找不到问题的根源,因此上传了整个代码。
// writing on a text file
#include <iostream>
#include <ctime>
#include <fstream>
using namespace std;
string encryptDecrypt(string toEncrypt) { //encryption,decryption function
char key = 'K'; //Any char will work
string output = toEncrypt;
for (int i = 0; i < toEncrypt.size(); i++)
output[i] = toEncrypt[i] ^ key;
return output;
}
int main () {
int mode;cout<<"Enter 1 to add new entry, 0 to see the diary\n"; cin>>mode;
ofstream f ("yourDiary.txt",ios::app);
time_t now=time(0);
char *ltm=ctime(&now);
string line,line2,pwd;
string encrypted = encryptDecrypt(ltm); //timestamp encrypted and added to file
string decrypted;
f<<encryptDecrypt("**"); //to find end of file
f<<"\n\n\n\n";
f << encrypted << "\n\n";
if(mode==1){
cout<<"speak your heart out. when you feel better enter **++**\n";
for(;;){
getline(cin,line);
if(line=="**++**"){
encrypted=encryptDecrypt(line);
f << encrypted <<"\n";
break; //end cuurrent data entry
}
else{
encrypted=encryptDecrypt(line);
f << encrypted <<"\n"; //line to file
}
}
f.close();
}
if (mode==0){
cout<<"enter password\n";
cin.ignore();
getline(cin,pwd);
if(pwd=="pwd"){ //encryption of password
ofstream dia("yourDiaryDecrypted.txt",ios::trunc);
fstream f("yourDiary.txt");
NEXT: getline(f,line);
decrypted=encryptDecrypt(line);
if (decrypted!="**++**"){
dia<<decrypted<<"\n";
goto NEXT; //restart loop
}
else{
getline(f,line2);
decrypted=encryptDecrypt(line2);
if(decrypted=="**"){
dia<<decrypted<<"\n";
goto NEXT; //restart loop
}
else{
goto EXIT; //break loop
}
}
EXIT: dia.close();f.close();
cout<<"You can now see your decrypted diary\n :)\n";
}
else{
cout<<"wait for the password. I will give it to you in due time\n";
}
}
cout<<"press enter to continue";
cin.ignore();
return 0;
}
谢谢。
最佳答案
我相信问题不在您的代码中,而是在您运行它并输入数据时出现的。当它以模式== 1询问时,我运行了您的代码
cout<<"speak your heart out. when you feel better enter **++**\n";
如果在创建yourDiary.txt时不键入**++**
,则将进入无限循环,因为
NEXT: getline(f,line);
decrypted=encryptDecrypt(line);
if (decrypted!="**++**"){
dia<<decrypted<<"\n";
goto NEXT;
如果您不输入
**++**
,它将永远不会找到它,因此它会不断循环播放。当我输入**++**
时它起作用了,或者您可以使用注释中建议的while循环代替goto。这需要在if(mode == 1)内部 f<<encryptDecrypt("**");
f<<"\n\n\n\n";
f << encrypted << "\n\n";
否则,如果您运行模式== 0,它将在yourdiary.txt中打印此内容;如果再次运行模式== 0,它将导致无限循环。