asyaevloeva
@asyaevloeva

Почему вылетает консоль, после выполнения программы?

Программа работает правильно, правильно подсчитывается количество слов в текстовом файле и правильно удаляются повторившиеся слова, но в конце появляется ошибка
Мой код
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;


int SIZE;

struct  WordCount
{
    string name;
    int count;
};

//сортировка слов
void bubbleSort(string arr[], int size)
{
    for (int stopMarker = 1; stopMarker < size; stopMarker++)
    {
        for (int j = size - 1; j >= stopMarker; j--)
        {
            if (arr[j] < arr[j - 1])
            {
                swap(arr[j], arr[j - 1]);
            }
        }
    }
}

//подсчет количества слов в текстовом файле
int lenCount(int nCount){
    //int fSpace = 1, nCount = 0;
    int fSpace = 1;
    nCount = 0;
        char ch[2] = {0};
        FILE *fh = fopen("./words.txt", "r");
        while (! feof(fh))
        {
            fgets(ch, 2, fh);
            if (ch[0] > 32)
                fSpace = 0;
            else if (0 == fSpace)
            {
                nCount++;
                fSpace = 1;
            }
            ch[0] = 0;
        }
        fclose(fh);
        //printf("%d\n", nCount);
        //cout << nCount;
        return nCount;
}


int main()
{
    int nCount = 0;
    int x = lenCount(nCount);
    //cout << x << endl;
    SIZE = x;
            cout << SIZE << endl;
    string wordArray[SIZE];
    string temp;
    WordCount arr[SIZE];
    WordCount item;


    ifstream input;

    input.open("./words.txt");



    for (int i = 0; i < SIZE; i++)
    {
        input >> wordArray[i];
        temp.erase(std::remove_if(temp.begin(), temp.end(), [](char c)
        {
            return c == ',' || c == '.' || c == '!';
        }),
            temp.end());
    }

    input.close();

    bubbleSort(wordArray, SIZE);

    int j = 0;
    for (int i = 0; j < SIZE; i++)
    {
        if (item.name != wordArray[j] && j < SIZE)
        {
            item.name = wordArray[j];
            item.count = 1;
            arr[i] = item;
            j = j + 1;
        }
        while (j < SIZE && item.name == wordArray[j])
        {
            item.count++;
            arr[i] = item;
            j = j + 1;
        }
    }



    for (int i = 0; i < 135; i++)
    {
        //cout << setw(13) << left << arr[i].name << setw(10) << "Count = " << arr[i].count << endl;
        cout << setw(13) << left << arr[i].name << setw(10) << endl;
        //cout << arr[i].name;
    }

    return 0;
}


Текст в текстовом файле:

Labor idea face Bush administration insistence training wage White House unrestricted six-month training wage time worker age job


Вывод:
5b8ce55327b54263b0785812521335dd.png
  • Вопрос задан
  • 780 просмотров
Решения вопроса 1
15432
@15432
Системный программист ^_^
for (int i = 0; j < SIZE; i++)

как минимум, здесь возможен выход i за пределы SIZE (проверка стоит на j вместо i).

падение происходит из-за проверки переполнения при завершении программы. где-то происходит выход за пределы выделенной памяти..
Ответ написан
Пригласить эксперта
Ответы на вопрос 2
devalone
@devalone
̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻̻
Бегло просмотрел код:
Вот здесь string wordArray[SIZE]; нужно использовать std::vector
Внутри этого цикла может быть выход за пределы массива
int j = 0;
for (int i = 0; j < SIZE; i++)

а может и не быть, если вы уверены в алгоритме, то всё ок
WTF?
for (int i = 0; i < 135; i++)
    {
        //cout << setw(13) << left << arr[i].name << setw(10) << "Count = " << arr[i].count << endl;
        cout << setw(13) << left << arr[i].name << setw(10) << endl;
        //cout << arr[i].name;
    }

Откуда магическое число 135?
И да, не используйте fopen раз уж пишите на C++
Ответ написан
@koronabora
Человек
Запусти в режиме отладки из под студии и она покажет место где появляется ошибка.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы