Сложности в создании функции обновления CRUD C ++ - PullRequest
0 голосов
/ 23 марта 2020

Итак, мне удалось создать все функции добавления, удаления и получения, но я застрял в функции обновления. Я перепробовал все, чтобы исправить это, и стало только хуже, поэтому я решил, что может понадобиться некоторая помощь. Я не могу понять, почему это не работает. filmul = mov ie (перевод) genul = жанр (перевод) Ниже приведена полная программа:

Film.cpp
#include "Film.h"
#include <iostream>
#include <ostream>

using namespace std;

Film::Film() {
    this->genul = NULL;
    this->titlul = NULL;
}

Film::Film(char* titlul, char* genul) {
    this->titlul = new char[strlen(titlul) + 1];
    strcpy_s(this->titlul, 1 + strlen(titlul), titlul);
    this->genul = new char[strlen(genul) + 1];
    strcpy_s(this->genul, 1 + strlen(genul), genul);

}

Film::Film(const Film& s) {
    cout << "copy constructor" << endl;
    this->titlul = new char[strlen(s.titlul) + 1];
    strcpy_s(this->titlul, 1 + strlen(s.titlul), s.titlul);
    this->genul = new char[strlen(s.genul) + 1];
    strcpy_s(this->genul, 1 + strlen(s.genul), s.genul);
}

char* Film::getTitlul() {
    return this->titlul;
}

char* Film::getGenul() {
    return this->genul;
}

void Film::setTitlul(char* titlul)
{
    if (this->titlul) {
        delete[] this->titlul;
    }
    this->titlul = new char[strlen(titlul) + 1];

    strcpy_s(this->titlul, strlen(titlul) + 1, titlul);
}

void Film::setGenul(char* genul)
{
    if (this->genul) {
        delete[] this->genul;
    }
    this->genul = new char[strlen(genul) + 1];

    strcpy_s(this->genul, strlen(genul) + 1, genul);
}

Film& Film::operator=(const Film& s) {
    this->setTitlul(s.titlul);
    this->setGenul(s.genul);
    return *this;
}

bool  Film::compare(Film& c) {
    return ((this->titlul == c.titlul));
}
bool Film:: operator==(const Film& s) {
    return strcmp(this->titlul, s.titlul) == 0 && strcmp(this->genul, s.genul) == 0;
}

ostream& operator<<(ostream& os, const Film& s)
{
    os << s.titlul << " " << s.genul;
    return os;
}
Film::~Film() {
    if (this->titlul) {
        delete[] this->titlul;
        this->titlul = NULL;
    }
}
main.cpp:
#include "Repository.h"
#include "ui.h"
#include <iostream>

using namespace std;

int main()
{

    Repository repo;

    Service service(repo);


    UI ui(service);

    ui.run();
}

Репозиторий


Repository::Repository() { size = 0; }

void Repository::addElement(Film s) {
    elem[size++] = s;
}
int Repository::findElement(Film s) {
    int i = 0;
    while (i < size) {
        if (elem[i] == s) return i;
    }
    return -1;
}

void Repository::updateElem(Film s2, char* n, char* v) {
    int i = findElement(s2);
    if (i!=-1)
    {
        elem[i].setTitlul(n);
        elem[i].setGenul(v); 
    }
}   

void Repository::deleteElement(Film s) {
    int i = findElement(s);
    if (i != -1)

    {
        elem[i] = elem[size - 1];

        --size;
    }

}

Film* Repository::getAll() {
    return elem;
}

int Repository::dim() {
    return size;
}

Repository::~Repository() {
}

Сервис

#include "Service.h"
#include <string>

void Service::addFilm(char* titlul, char* genul)
{
    Film st(titlul, genul);
    this->repo.addElement(st);
}
void Service::deleteFilm(char* titlul, char* genul) {
    Film st(titlul, genul);
    this->repo.deleteElement(st);
}
void Service::updateFilm(char* titlul, char* genul) {
    //Film st(titlul, genul);
    //this->repo.updateElem(st, titlul, genul);

    Film* film = repo.getAll();
    //char* genulvechi;
    int n = repo.dim();

    //Film rezultat[10];
    for (int i = 0; i < n; ++i)
    {//strstr
        if (film[i].getTitlul() == titlul)

            //Film f2 = film[i];
            //this->repo.updateElem(film[i], film[i].getTitlul(), genul);
        //rezultat.push_back(film[i], genul);
        //this->repo.deleteElement(film[i
        //genulvechi = film[i].getGenul();
        deleteFilm(titlul, film[i].getGenul());
        Film f3(titlul, genul);
        this->repo.addElement(f3);


    }
}

ui. cpp

#include "ui.h"
#include <iostream>
#include <vector>

using namespace std;

void UI::showMenu() {
    cout << "1.Afisare toate filmele" << endl;
    cout << "2.Adaugare film" << endl;
    cout << "3.Stergere film" << endl;
    cout << "4.Iesire" << endl;
    cout << "5.Update film" << endl;
}

vector<int> arr;

void UI::run() {
    while (true)
    {
        showMenu();
        char optiune;
        Film* rez;
        cout << "Optiune: "; cin >> optiune;
        switch (optiune)
        {
        case '1':
            rez = service.getAll();
            for (int i=0;i < arr.size(); ++i)
            {
                cout << i + 1 << ". " << rez[i].getGenul() << " - " << rez[i].getTitlul() << endl;
            }
            break;


        case '2':
            char titlul[30];
            char genul[30];
            cout << "Titlul filmului: "; cin >> titlul;
            cout << "Genul filmului: "; cin >> genul;
            service.addFilm(titlul, genul);
            arr.push_back(1);
            break;

        case '3':
            char titlul2[30];
            char genul2[30];
            cout << "Titlul filmului: "; cin >> titlul2;
            cout << "Genul filmului: "; cin >> genul2;
            service.deleteFilm(titlul2, genul2);
            arr.pop_back();
            break;
        case '4':
            return;
        default:
            cout << "Comanda invalida!" << endl;
        case '5':
            char titlul3[30];
            char genul3[30];
            char gen[10];
            cout << "Titlul filmului: "; cin >> titlul3;
            cout << "Genul vechi al filmului:"; cin >> gen;
            cout << "Genul nou al filmului: "; cin >> genul3;
            /*
            service.deleteFilm(titlul3, gen);
            arr.pop_back();
            service.addFilm(titlul3, genul2);*/
            //service.deleteFilm(titlul3, gen);
            service.updateFilm(titlul3, genul3);
            arr.push_back(1);
            break;
        }
    }
}

Я работал над функцией обновления, и она не работала должным образом, вместо этого только добавляя новый элемент без удаления старого. СПАСИБО !!!

1 Ответ

0 голосов
/ 23 марта 2020

Преобразование всех моих исходных комментариев в ответ.

У вас есть много ошибок, которые нужно исправить:

  • Ваш код будет вдвое сложнее, если вы использовал класс std::string вместо использования буферов char* и обработки операций выделения / копирования вручную. В основном это устранит ошибки, о которых я расскажу ниже.

  • Вызов film->setTitlul(film->getTitlul()) генерирует неопределенное поведение, поскольку удаляет старый член перед выделением нового члена.

  • Следовательно, самостоятельное назначение экземпляра Film (например, Film f1; f1 = f1) приводит к аналогичной ошибке.

  • Я не вижу конструктора для Film, поэтому я ' Осталось предположить, что элементы titlul и genul являются указателями мусора при создании экземпляра. Не сулит ничего хорошего для вызова delete в этих методах set.

  • Repository::deleteElement содержит ошибки - особенно для элементов, находящихся не в конце массива. Удаление из середины массива означает, что вам нужно сместить все элементы больше индекса на 1. Ваша реализация смещает только один элемент слева. Неправильный счет. Неправильное направление.

  • В Service::updateFilm эта строка, if (film[i].getTitlul() == titlul) сравнивает указатели вместо выполнения strcmp. В этом суть вашей проблемы, но это не единственная ошибка.

Я собираюсь на этом остановиться. Вероятно, есть и другие ошибки, но вы должны отладить их самостоятельно.

...