2015-09-05 23 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

谢谢;这真的很有帮助 –