Массив получает tra sh после добавления нового файла в файл С ++ Visual Studio - PullRequest
0 голосов
/ 30 апреля 2020

Я пытаюсь решить задачу со структурами, динамическими c массивами и файлами. Итак, я

  1. создаю массив c Dynami - Unit* array_of_employees = new Unit[number_of_employees];
  2. создаю массив - generateEmployees(Unit* array_of_employees, int& number_of_employees);
  3. записываю данные в файл - writeFileEmployees(Unit* array_of_employees, int number_of_employees);
  4. отображение элементов массива в консоли - readAllEmployeeData(Unit* array_of_employees, int number_of_employees);

До этого момента он работал правильно. Затем я

  1. перераспределяю память массива путем создания нового массива с объемом памяти +1 - Unit* getRememberForArrayOfEmployees(Unit* array_of_employees, int& number_of_employees, int new_number_of_employees);
  2. и добавляю новую заметку в конец массива
  3. запись в конец файла - void writeEndFileEmployees(Unit new_epmloyee);

Затем я пытаюсь показать массив в консоли, но в массиве есть тра sh. Нужна ваша помощь

#include <conio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

struct Unit
{
    string fullName;
    string department;
    string position;
    int monthSalary;
};

const string FILE_OF_EMPLOYEES = "employee.txt"; //file_path

int getCountOfEmployees(string FILE_OF_EMPLOYEES);
void generateEmployees(Unit* array_of_employees, int& number_of_employees);
void writeFileEmployees(Unit* array_of_employees, int number_of_employees);
void writeEndFileEmployees(Unit new_epmloyee);
void readAllEmployeeData(Unit* array_of_employees, int number_of_employees);
void addNewEmployeeData(Unit* array_of_employees, int& number_of_employees);
Unit* getRememberForArrayOfEmployees(Unit* array_of_employees, int& number_of_employees, int new_number_of_employees);

int main()
{
    setlocale(LC_ALL, "rus");

    int number_of_employees = getCountOfEmployees(FILE_OF_EMPLOYEES);
    Unit* array_of_employees = new Unit[number_of_employees];

    generateEmployees(array_of_employees, number_of_employees);
    writeFileEmployees(array_of_employees, number_of_employees);
    readAllEmployeeData(array_of_employees, number_of_employees);
    addNewEmployeeData(array_of_employees, number_of_employees);

    //From this place there is trash in the array_of_employees :(

    readAllEmployeeData(array_of_employees, number_of_employees);

    delete[]array_of_employees;
    system("pause");
    return 0;
}


//Define amount of structures in the file
int getCountOfEmployees(string FILE_OF_EMPLOYEES)
{
    //Open and move a cursor in the end of the file
    ifstream file(FILE_OF_EMPLOYEES, ios::in);
    int number_of_strings = 0;
    if (file.is_open())
    {
        string buffer;
        while (getline(file, buffer))
            number_of_strings++;
    }
    file.close();
    return number_of_strings;
}

void generateEmployees(Unit* array_of_employees, int& number_of_employees)
{
    number_of_employees = 1;

    array_of_employees[0].fullName = "Ivanov";
    array_of_employees[0].department = "QA1";
    array_of_employees[0].position = "QA";
    array_of_employees[0].monthSalary = 1000;
}

void writeFileEmployees(Unit* array_of_employees, int number_of_employees)
{
    ofstream fout(FILE_OF_EMPLOYEES, ios::out);
    for (int i = 0; i < number_of_employees; i++)
    {
        fout << array_of_employees[i].fullName << " "
            << array_of_employees[i].department << " "
            << array_of_employees[i].position << " "
            << array_of_employees[i].monthSalary;
        if (i < number_of_employees - 1) fout << endl;
    }
    fout.close();
}

void writeEndFileEmployees(Unit new_employee)
{
    ofstream fadd(FILE_OF_EMPLOYEES, ios::app);
    fadd << endl;
    fadd << new_employee.fullName << " "
        << new_employee.department << " "
        << new_employee.position << " "
        << new_employee.monthSalary;
    fadd.close();
    cout << "New employee added" << endl;
}

void readAllEmployeeData(Unit* array_of_employees, int number_of_employees)
{
    //system("cls");
    cout << "  Users accounts\n"
        << " ------------------------------- \n"
        << "|Full Name"
        << "\t|Department"
        << "\t|Position"
        << "\t|Monthly Salary\t|\n"
        << "\n ------------------------------- \n";
    for (int i = 0; i < number_of_employees; i++)
    {
        cout << "|" << array_of_employees[i].fullName << " "
            << "\t|" << array_of_employees[i].department << "\t"
            << "\t|" << array_of_employees[i].position << "\t"
            << "\t|" << array_of_employees[i].monthSalary << "\t|"
            << endl;
    }
    cout << " ------------------------------- " << endl;
}

void addNewEmployeeData(Unit* array_of_employees, int& number_of_employees)
{
    //system("cls");
    array_of_employees = getRememberForArrayOfEmployees(array_of_employees, number_of_employees, number_of_employees + 1);
    cout << "Add new user profile\n" << endl;
    cout << "Full Name: ";
    cin >> array_of_employees[number_of_employees - 1].fullName;
    cout << "Department: ";
    cin >> array_of_employees[number_of_employees - 1].department;
    cout << "Position: ";
    cin >> array_of_employees[number_of_employees - 1].position;
    cout << "Monthly salary: ";
    cin >> array_of_employees[number_of_employees - 1].monthSalary;

    writeEndFileEmployees(array_of_employees[number_of_employees - 1]);

}

Unit* getRememberForArrayOfEmployees(Unit* array_of_employees, int& number_of_employees, int new_number_of_employees)
{
    Unit* new_array_of_employees;
    if (number_of_employees < new_number_of_employees)
    {
        new_array_of_employees = new Unit[new_number_of_employees];
        for (int i = 0; i < number_of_employees; i++)
        {
            new_array_of_employees[i].fullName = array_of_employees[i].fullName;
            new_array_of_employees[i].department = array_of_employees[i].department;
            new_array_of_employees[i].position = array_of_employees[i].position;
            new_array_of_employees[i].monthSalary = array_of_employees[i].monthSalary;

        }
        for (int i = number_of_employees; i < new_number_of_employees; i++)
        {
            new_array_of_employees[i].fullName = " ";
            new_array_of_employees[i].department = " ";
            new_array_of_employees[i].position = " ";
            new_array_of_employees[i].monthSalary = 0;
        }
        delete[]array_of_employees;
        number_of_employees = new_number_of_employees;
        array_of_employees = new_array_of_employees;
    }
    return array_of_employees;
}

1 Ответ

0 голосов
/ 30 апреля 2020

addNewEmployeeData (через вызов getRememberForArrayOfEmployees) может удалить существующие данные array_of_employees. Вы выделяете для этого новый массив, но никогда не передаете измененный указатель вызывающей стороне.

Вы должны передать array_of_employees в качестве ссылки (Unit *&array_of_employees), как вы делаете с number_of_employees.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...