2013-06-30 24 views
1

由於我開始搞亂XOR操作符和簡單的單字符密鑰加密,我遇到了以前從未見過的問題。該文本在第二次運行程序後,始終在其結尾處具有隨機ASCII字符。另一個問題是,在程序的每次迭代之後,文本「預訂」和「後序」都會被修改。我相信這其中的大部分是由於初學者的錯誤,尤其是在IO方面缺乏這些問題出現的經驗。C++中的cout,XOR和fileIO格式化問題

#include <iostream> 
#include <string> 
#include <fstream> 
using namespace std; 

int main() 
{ 
    ifstream ifile; 
    ofstream ofile; 
    string toProc; 
    string file; 
    char key = ' '; 
    cout << "Enter file location: \n"; 
    cin >> file; 
    cout << "Enter key: \n"; 
    cin >> key; 
    ifile.open(file); 
    if(ifile.is_open()) 
    { 
     char temp; 
     temp = ifile.get(); 
     toProc.push_back(temp); 
     while(ifile.good()) 
     { 
      temp = ifile.get(); 
      toProc.push_back(temp); 
     } 

     ifile.close(); 
    } 
    else 
    { 
     cout << "No file found.\n"; 
    } 
    cout << "Pre action: " << toProc << endl; 
    for(int i = 0; i < toProc.size(); i++) 
     toProc[i] ^= key; 
    cout << "Post action: " << toProc << endl; 
    ofile.open(file); 
    ofile << toProc; 
    ofile.close(); 
} 

回答

2

std::ifstreamget()功能,您可以使用它從輸入文件中檢索字符,返回eof(結束文件),當它遇到文件的末尾。你需要檢查這個(而不是在循環中檢查ifile.good())。

它現在寫的方式,它將eof作爲一個字符並將其附加到字符串。那個(即它的異或版本)是你在輸出中獲得的有趣角色。

這是一個簡單的循環,它使用get()std::cin中讀取字符,並在STDOUT上回顯它們。它會正確執行eof的檢查。你能適應這個到你的代碼,使用ifile代替std::cin

#include <iostream> 

int main() 
{ 
    char c; 
    while ((c = std::cin.get()) != std::istream::traits_type::eof()) 
    std::cout.put(c); 

    std::cout << std::endl; 
    return 0; 
} 

我還要提到的是,get()功能通過字符讀取字符,並沒有什麼好的理由。我會用getline()read()來讀取更大的塊。

+1

請注意,getLine()對解密部分不起作用,因爲加密的結果可能包括各種控制字符。爲了執行有意義的加密,你應該使用明確的字符編碼(但是再次,你不應該使用單個字符加密,爲了測試的目的,你應該能夠避開它)。 –

+0

@owlstead啊,是的,沒錯。我曾以某種方式假定加密僅適用於這裏的字母字符,但您是對的,它也會影響行結尾。 – jogojapan

+0

謝謝!檢查完eof後完成工作。文件IO始終是我的一個問題。 – Aer