c++中的意外中止

Unexpected abort in C++

本文关键字:意外 c++      更新时间:2023-10-16

我有一段代码,我在Cygwin在c++中运行,我正在编译使用

g++ -o program program.cpp

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

您从未为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将字符串映射到计数来更简单地做到这一点。