2016-08-02 41 views
0

我正在嘗試編寫一個凱撒密碼的程序,現在我正在尋找移動密碼的關鍵函數。問題雖然通過函數讀取文件

現在出現的問題是,同時在讀取文件時,程序中斷和我得到的錯誤:

「異常在ConsoleApplication11.exe在0x89012914拋出:0000005:訪問衝突執行位置0x89012914 如果有是這個例外的處理程序,程序可以安全地繼續。「

這是我到目前爲止的代碼,有沒有什麼明顯的我可以忽略?

int findKey(string& file); 

int main() 
{ 

    string inputFileName; 


    cout << "Input file name: "; 
    getline(cin, inputFileName); 

    findKey(inputFileName); 




} 

int findKey(string& file) 
{ 
    string reply; 
    ifstream inFile; 
    char character; 
    int count[26] = { 0 }; 
    int nGreatest = 0; 

    inFile.open(file.c_str()); 

    if (!inFile.is_open()) 
    { 
     cout << "Unable to open input file." << endl; 
     cout << "Press enter to continue..."; 
     getline(cin, reply); 
     exit(1); 

    } 

    while (inFile.peek() != EOF) 
    { 
     inFile.get(character); 
     cout << character; 

     if (int(character) >= 65 || int(character) <= 90) 
     { 
      count[(int(character)) - 65]++; 
     } 
     else if (int(character) >= 97 || int(character) <= 122) 
     { 
      count[(int(character)) - 97]++; 
     } 
    } 

    for (int i = 0; i < 26; i++) 
    { 
     if (count[i] > nGreatest) 
      nGreatest = count[i]; 

    } 

    cout << char(nGreatest) << endl; 

    return 0; 
} 
+0

[看看這個](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Rakete1111

回答

1
if (int(character) >= 65 || int(character) <= 90) 

由於換行符,'\n'ASCII 10,小於或等於90,這if聲明將評估爲真,並...

count[(int(character)) - 65]++; 

..嘗試增加count[10-65]count[-55]。從這個角度來看,事情幾乎要失敗了(因爲每個角色都是至少65,或者小於或等於90,這總是評估爲true)。

P.S.我花了幾分鐘的時間找到這個bug,使用調試器,單步執行代碼,一次一行(我自己無法立即看到它)並檢查所有變量。您應該花一些時間學習如何使用調試器。更容易找到自己的錯誤,而不必問在交互管道上的陌生人,尋求幫助。

+0

好吧,這使得很多感覺,現在會將它從一個OR改爲一個AND來解決這個問題? – WittyUsernameHere

+0

那麼,你有沒有嘗試過,如果沒有,爲什麼不呢?您不需要任何人的許可就可以更改自己的代碼,並查看它是否正常工作。 –