gpt4 book ai didi

c++ - 当要读取的文件已经打开时,文件读取进入无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 13:02:42 25 4
gpt4 key购买 nike

我写这段代码是为了制作日记或日记。它接受输入,对其进行加密并将其存储在名为“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";

否则,如果您运行 mode == 0,它将在 yourdiary.txt 中打印此内容,如果您再次运行 mode == 0,则会导致无限循环。

关于c++ - 当要读取的文件已经打开时,文件读取进入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43574815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com