2015-09-05 51 views
-2

我有一段代碼我在Cygwin的用C++運行我使用意外中止在C++

g++ -o program program.cpp 

編譯和它返回讀取「中止(核心轉儲)」的誤差。它旨在通過命令行參數輸入文件名作爲輸入,計算文件中所有唯一字和全部單詞,並提示用戶輸入單詞並計算它們輸入的單詞的發生次數。它只打算使用C++流進行輸入/輸出。

#include <fstream> 
    #include <iostream> 
    #include <string> 
    #include <cctype> 
    using namespace std; 
    int main(int argc, char *argv[]) 
    { 
     string filename; 
     for(int i = 1; i < argc; i++){ 
      filename+=argv[i]; 
     } 
     ifstream file; 
     file.open(filename.c_str()); 
     if (!file) 
     { 
      std::cerr << "Error: Cannot open file" << filename << std::endl; 
      return 1; 
     } 
     string* words; 
     int* wordCount; 
     int wordLength = 0; 
     string curWord = ""; 
     bool isWord; 
     int total = 0; 
     char curChar; 
     string input; 
     while(!file.eof()) 
     {   
      file.get(curChar); 
      if (isalnum(curChar)) { 
       curWord+=tolower(curChar); 
      } 
      else if (!curWord.empty() && curChar==' ') 
      { 
       isWord = false; 
       for (int i = 0; i < wordLength; i++) { 
        if (words[i]==curWord) { 
         wordCount[i]++; 
         isWord = true; 
         total++; 
        } 
       } 
       if (!isWord) { 
        words[wordLength]=curWord; 
        wordLength++; 
        total++; 
       } 
       curWord=""; 
      } 
     } 
     file.close(); 
     // end 
     cout << "The number of words found in the file was " << total << endl; 
     cout << "The number of unique words found in the file was " << wordLength << endl; 
     cout << "Please enter a word: " << endl; 
     cin >> input; 
     while (input!="C^") { 
      for (int i = 0; i < wordLength; i++) { 
       if (words[i]==input) { 
        cout << wordCount[i]; 
       } 
      } 
     } 
    } 
+2

當您使用調試器時,哪個語句是中止前執行的最後一個語句?您在發佈之前確實使用了調試器,不是嗎? –

+1

也許不相關,但請參閱http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong – Barmar

+0

我不確定你的意思;是否有一個內置於cygwin中的C++調試器?在我發佈之前,我一行一行地檢查代碼以檢查錯誤。 –

回答

1

你從來沒有分配任何空間wordswordCount指向。它應該是:

#define MAXWORDS 1000 
string *words = new string[MAXWORDS]; 
int *wordCount = new int[MAXWORDS]; 

,然後在程序結束時,你應該做的:

delete[] wordCount; 
delete[] words; 

,或者你可以分配一個本地數組:

string words[MAXWORDS]; 
int wordCount[MAXWORDS]; 

但你可以做到這一點更簡單地通過使用std::map將字符串映射到計數。這將根據需要自動增長。

+0

'words'變量具有相同的問題。 –

+0

是的,只是補充說。 – Barmar

+0

謝謝;這真的很有幫助 –