(第一篇博客,但願你們多多支持!仍是初學者,如有問題或更好的看法請在評論區指出,歡迎交流!)html
1、問題描述ios
Write an encryption program that reads from cin (a file)and writes the encoded characters to cout (a file).c++
You might use this simple encryption scheme: the encrypted form of a character c is c^key[i], where key is a string passed as a command-line argument. The program uses the characters in key in a cyclic manner until all the input has been read. Re-encrypting encoded text with the same key produces the original text. If no key (or a null string) is passed, then no encrption is done.this
2、問題解決加密
1.thinkingspa
建立三個文件:in.txt(用於讀入)、out.txt(加密結果存儲)、original.txt(解密結果存儲)。命令行
讀入文件,進行後續加密解密操做;若讀入失敗,進行異常處理。code
2.importantorm
①.瞭解c++的位運算(此處主要爲 ^ 異或運算)htm
②.關於文件的一些處理
3.process
①.關於 異或 運算
能夠看出,異或運算返回值是int,而char ^ int實際對char進行了隱式類型轉換。
另外,咱們須要以char類型從in.txt文件中讀入,以int類型從out.txt中讀入。
異或運算有一些特殊用途:1.一個數異或兩次是自己。2.一個數與0異或會保留原值(1001 1001 ^ 0000 0000 -> 1001 1001)
②.關於文件的讀入和EOF
關於EOF的詳細解釋:https://www.cnblogs.com/dolphin0520/archive/2011/10/13/2210459.html
在文件讀入時,每次讀入以後都應判斷是否讀到EOF。固然寫法根據具體狀況而定。在此題中,若將讀入寫入循環體,判斷條件爲while(!f_in.eof())會出現不可預測的問題,即便文件已經讀完,但循環不會終止!
4.result
分享源碼
1 #include<iostream> 2 #include<fstream> 3 #include<cstring> 4 5 using namespace std; 6 7 int main(int argc,char** argv) 8 { 9 ifstream fin("in.txt"); 10 if (!fin.is_open()) { 11 cout << "Can't open file \"in.txt\""; 12 return -1; 13 } 14 15 fstream fout("out.txt"); 16 if (!fout.is_open()) { 17 cout << "Can't open file \"out.txt\""; 18 return -1; 19 } 20 21 if(strlen(argv[1]) == 0){ //若沒receive到命令行參數,則不進行加密解密 22 string temp; 23 cout<<"No key . No encryption ."<<endl; 24 while(fin>>temp){ 25 fout<<temp; 26 } 27 return 0; 28 } 29 30 char temp; 31 int i = 0; 32 33 while (fin.get(temp)) //加密運算 34 { 35 fout << (temp ^ argv[1][strlen(argv[1]) - i % strlen(argv[1])]) << ' '; 36 i++; 37 } 38 39 fin.close(); 40 fout.close(); 41 42 cout << "Encryption has done ." << endl 43 << "Now begin re-encrypting ." << endl; 44 45 ifstream f_in("out.txt"); 46 if (!f_in.is_open()) { 47 cout << "Can't open file \"out.txt\""; 48 return -1; 49 } 50 51 ofstream f_out("original.txt"); 52 if (!f_out.is_open()) { 53 cout << "Can't open file \"original.txt\""; 54 return -1; 55 } 56 57 i = 0; 58 int temp_1; 59 while (f_in >> temp_1) { //解密運算,此處須要進行強制類型轉換輸出字符 60 f_out << char((temp_1 ^ argv[1][strlen(argv[1]) - i % strlen(argv[1])])); 61 i++; 62 } 63 64 cout << "Re-encryption has done." << endl; 65 return 0; 66 }