C ++中出现意外中止

时间:2015-09-05 00:02:23

标签: c++

我有一段代码我在Cygwin中用C ++运行我正在使用

进行编译
g++ -o program program.cpp

它返回一个错误,上面写着'Aborted(core dumped)'。它旨在通过命令行参数获取文件名作为输入,计算文件中的所有唯一单词和总单词,并提示用户输入单词并计算他们输入的单词出现的次数。它只是用于输入/输出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];
                }
            }
        }
    }

1 个答案:

答案 0 :(得分: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将字符串映射到计数来更简单地做到这一点。这将根据需要自动增长。