为什么我在 C++ 中遇到分段错误?

时间:2021-05-04 03:10:14

标签: c++

#include <iostream>
#include <ctime>
#include <fstream>
#include <cstdlib>

using namespace std;

class Words {
private:
    int minlen;
    int maxlen;
    int count;
    string* choices;

    int count_candidates()
    {
        ifstream fin;

        fin.open("enable1.txt");
        int count = 0;
        if (fin.is_open()) {
            string word;

            while (!fin.eof()) {
                word = fin.get();
                if (word.length() >= minlen && word.length() <= maxlen) {
                    if (fin.good()) {
                        count++;
                    }
                }
            }
        }
        fin.close();
        return count;
    }
    void load_words()
    {
        string* choices = new string[count];

        ifstream fin;

        fin.open("enable1.txt");
        int count = 0;
        if (fin.is_open()) {
            string word;

            while (!fin.eof()) {
                word = fin.get();
                if (word.length() >= minlen && word.length() <= maxlen) {
                    if (fin.good()) {
                        for (int i = 0; i < count; i++) {
                            choices[i] = word;
                        }
                    }
                }
            }
            fin.close();
        }
    }

public:
    Words(int max, int min)
    {
        minlen = min;
        maxlen = max;
    }
    string pick_word()
    {
        if (count == 0) {
            return " ";
        }
        else {
            srand(time(0));
            return choices[rand() % count];
        }
    }
    ~Words()
    {
        if (choices != NULL) {
            delete[] choices;
        }
    }
};

int main()
{
    srand(time(NULL)); // needs <ctime> included
    int min, max;

    cout << "Enter min: ";
    cin >> min;

    cout << "Enter max: ";
    cin >> max;

    Words words(min, max);

    cout << words.pick_word() << endl;
}

我已经遵守了它,它可以工作,但我遇到了分段错误

对于文本文件,打开 PowerShell 并输入 cp /home/fac/mmanibo/shared/enable1.txt 。 我不知道我是否可以在我的域外共享此内容。

我想得到一个像:

[Run your program]
Enter min: 27
Enter max: 29
electroencephalographically

0 个答案:

没有答案