编写程序进行简易的加密解密

黄锭宪 2019-05-18 02:15:33
已知文件input.txt,逐一读入文件中的字符,将其中的字符的ASCII码+数字(1~9),再逐一写入到code.txt中。 已知文件code.txt,将其解码后输出到output.txt中。 对比input.txt和output.txt(提示:可使用system(“fc input.txt output.txt”)) 要求有如下菜单 ------------------------------ 菜单 ------------------------------ 1. 退出 2. 加密文件 3. 解密文件 4. 比较文件 ----------------------------- 本人不会将其中的字符的ASCII码+数字(1~9)这部分,求大神,还有解密该怎么解,下面是本人写的代码 #include<iostream> #include<fstream> #include<string> using namespace std; void Menu1(); char ch; char filename[40]; char infilename[40]; int number1; int number2; void Menu1() { cout << "-----------------------------" << endl; cout << " 菜单" << endl; cout << "-----------------------------" << endl; cout << "\t0. 退出" << endl; cout << "\t1. 加密文件" << endl; cout << "\t2. 解密文件" << endl; cout << "\t3. 比较文件" << endl; cout << "-----------------------------" << endl; cout << "请输入选择:(0~3)" << endl; } void Encrytfile(); void Encrytfile() { cout << "请输入你要加密的文件名" << endl; cin >> infilename; cout << "请输入密码(1~9):" << endl; cin >> number1; ifstream infile; infile.open(infilename, ios::in); if (infile.fail()) { cout << "无法打开文件" << endl; return; } ofstream outfile; outfile.open("code.txt", ios::out); if (outfile.fail()) { cout << "无法打开文件" << endl; return; } while (infile.get(ch)) outfile << ch + number1; infile.close(); outfile.close(); } void DeclassifiedFile(); void DeclassifiedFile() { cout << "请输入你要解密的文件名" << endl; cin >> filename; cout << "请输入密码(1~9):" << endl; cin >> number2; ifstream in; in.open(filename, ios::in); if (in.fail()) { cout << "无法打开文件" << endl; return; } ofstream out; out.open("output.txt"); if (out.fail()) { cout << "无法打开文件" << endl; return; } while (in.get(ch)) out << ch - number2; in.close(); out.close(); } void Comparefile(); void Comparefile() { system("fc input.txt output.txt"); } int main() { int userchoice1; do { Menu1(); cin >> userchoice1; switch (userchoice1) { case 0: return 0; case 1: Encrytfile(); case 2: DeclassifiedFile(); case 3: Comparefile(); } } while (userchoice1 != 0); } 但是解密出来和原来不一样
...全文
229 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
轻箬笠 2019-05-18
  • 打赏
  • 举报
回复
楼主关键要知道,加密和解密文件一定要用二进制流的形式进行读写。
infile.open(infilename, ios::in | iso::binary);
另外,如果文件不长的话,建议一次性读取全部文件内容,然后对每个字节进行加减的操作(或者抑或,或者抑或+加减),然后再以二进制流的形式写入到新的文件中。


而在windows环境下,默认情况下,是以ansi格式读写的。你这样在读到的ansi数据上面进行加减肯定是不行的。
636f6c696e 2019-05-18
  • 打赏
  • 举报
回复
核心问题是输出格式不对,应该用字符输出,这就是C++输出流不好的地方了 改成下面这样: out << (char)(ch - number2); out << (char)(ch + number1);
黄锭宪 2019-05-18
  • 打赏
  • 举报
回复
求大神求大神求大神求大神

64,642

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧