41

(8 відповідей, залишених у C++)

Панове, є така проблема:
У мене некоректно працює код для ось цього завдання:
переставити фрагмент тексту (декілька абзаців)
( запитує номер першого абзацу і номер останнього абзацу фрагменту, що переставляється
( запитує номер абзацу, після якого цей фрагмент вставити
( тоді вилучає фрагмент зі старого місця та вставляє у нове

Якщо я вводжу такі от цифри
номер першого абзацу : 2
номер останнього абзацу : 4
після якого абзацу вставити : 5

то результат вийде такий:
1. 1
2. 5
3. пусто
4. пусто
5. пусто
6. 6
7. 7
Ось код методу :

    void replaceParagraphs()
    {
        int indexFirst;
        int indexLast;
        int indexPut;
        if (myText.size() >= 2)
        {
            do
            {
                cout << "Enter the number of the first paragraph of a range : ";
                cin >> indexFirst;
                indexFirst--;
                //cout << myText[indexFirst] << endl;
                cout << "Enter the number of the last paragraph of a range : ";
                cin >> indexLast;
                indexLast--;
                //cout << myText[indexLast] << endl;
                cout << "Enter the number of paragraph after wich the range should be put :";
                cin >> indexPut;
                indexPut--;
                //cout << myText[indexPut] << endl;
                //system("pause");
                if (indexPut >= indexFirst && indexPut <= indexLast)
                {
                    throw "The range cannot be inserted inside itself!";
                }
            } while (indexFirst < 0 && indexFirst > myText.size() && indexLast < 0 && indexLast > myText.size() - 1);
            if (indexFirst > indexLast)
            {
                swap(indexFirst, indexLast);
            }
            vector<string>::const_iterator iter = myText.begin() + (indexPut + 1);
            if (iter < myText.begin() || iter > myText.end())
            {
                throw "Invalid PUT index. Put index is out of range";
            }
            myText.insert(iter, myText.begin() + indexFirst, myText.begin() + (indexLast + 1));
            //this->showText(0);
            //system("pause");
            if (indexPut >= indexLast)
            {
                myText.erase((myText.begin() + indexFirst), (myText.begin() + (indexLast + 1)));
            }
            else if (indexPut < indexFirst)
            {
                myText.erase(myText.begin() + (indexFirst + (indexLast - indexFirst + 1)), myText.begin() + (indexLast + (indexLast - indexFirst + 2)));
            }
        }
        else
        {
            throw "Too few elements in the vector to manipulate them!";
        }
    }

Ось код всієї програми + прикріпив файлик, щоб зчитати:

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <fstream>
#include <windows.h>
#include <string>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <locale>

using namespace std;

class Editor
{
private:
    vector<string> myText;
    fstream myTextEditor;
    string file_name;
public:
    Editor()
    {
        myText = {};
        file_name = "NewFile.txt";
    };


    void createFile()
    {

        string fileName;
        cout << "Type in file name : ";
        cin.ignore();
        getline(cin, fileName);

        /*cout << "Type in directory where to create the file : ";
        string dir;
        getline(cin, dir);
        string path = dir + fileName;*/
        ofstream someFile;
        someFile.open(fileName, ios_base::out);
        someFile.close();
    }

    /*+ відкрити існуючий файл
    ( запитує ім'я файлу)*/

    void openFile()
    {
        string fileName;
        cout << "Type in name of the file to oopen :";
        cin.ignore();
        getline(cin, fileName);
        ifstream readFile;
        readFile.open(fileName, ios_base::in);
        if (!readFile.is_open())
        {
            throw 1;
        }
        else
        {
            string readText;
            while (!readFile.eof())
            {
                getline(readFile, readText);
                myText.push_back(readText);
            }
        }
        readFile.close();
    }

    /*зберегти текст у файл
    ( запитує ім'я файлу і зберігає текст у цей файл*/
    void saveText()
    {
        string fileName;
        cout << "Enter file name to save text :";
        cin.ignore();
        getline(cin, fileName);
        ofstream writeFile;
        writeFile.open(fileName, ios_base::out);
        if (!writeFile.is_open())
        {
            throw 2;
        }
        else
        {
            vector<string>::iterator iter = myText.begin();
            for (; iter != myText.end() - 1; ++iter)
            {
                writeFile << *iter << endl;
            }
            writeFile << *iter;
            writeFile.close();
        }
    }

    void addParagraph()
    {
        string paragraph;
        cout << "Enter new paragraph : " << endl
            << "**********" << endl;
        cin.ignore();
        getline(cin, paragraph);
        myText.push_back(paragraph);
        cout << endl << "New paragraph added!" << endl << endl;
    }

    /*+ редагувати абзац
    ( запитує номер абзацу і замінює його вміст введеним з клавіатури текстом*/
    void editParagraph()
    {
        int index;
        string newParag;
        do
        {
            cout << "Enter number of paragraph to edit : ";
            cin >> index;
        } while (index - 1 < 0 && index - 1 > myText.size());
        cout << "Type in new text of the paragraph :" << endl;
        cin.ignore();
        getline(cin, newParag);
        myText.insert(myText.begin() + (index - 1), newParag);
        myText.erase(myText.begin() + index);
    }

    void clearVector()
    {
        char choice;
        do
        {
            cout << "Are you sure you want to clear the vector? y/n : ";
            cin >> choice;
        } while (choice != 'y' && choice != 'n');

        if (choice == 'y')
        {
            myText.clear();
            cout << "Vector is empty!" << endl;
        }
        else
        {
            cout << "Canceled" << endl;
        }
        system("pause");
    }

    /*+ показати текст
    ( поекранно виводить понумерований список абзаців
    (    ( абзац -- це текст, що завершується символом нового рядка '\n'
    (     ( поекранно -- означає, що після виводу на екран 24 рядків (не абзаців) запитує ( Continue (y/n) ? )*/
    void showText(int index)
    {
        char choice;
        cout << "Vector capasity = " << myText.capacity() << endl;
        cout << "Vector size = " << myText.size() << endl;
        for (int i = index; i < myText.size(); ++i)
        {
            if (i == (index + 7))
            {
                do
                {
                    cout << setw(20) << right << "Continue (y/n) ? : ";
                    cin >> choice;
                } while (choice != 'y' && choice != 'n');
                switch (choice)
                {
                case 'y':
                {
                    showText(i);
                    return;
                }
                case 'n': return;
                default:
                    break;
                }
            }
            cout << i + 1 << ", " << myText[i] << endl;
        }
        system("pause");
    }

    /*+ переставити фрагмент тексту (декілька абзаців)
    ( запитує номер першого абзацу і номер останнього абзацу фрагменту, що переставляється
    ( запитує номер абзацу, після якого цей фрагмент вставити
    ( тоді вилучає фрагмент зі старого місця та вставляє у нове*/

    void replaceParagraphs()
    {
        int indexFirst;
        int indexLast;
        int indexPut;
        if (myText.size() >= 2)
        {
            do
            {
                cout << "Enter the number of the first paragraph of a range : ";
                cin >> indexFirst;
                indexFirst--;
                //cout << myText[indexFirst] << endl;
                cout << "Enter the number of the last paragraph of a range : ";
                cin >> indexLast;
                indexLast--;
                //cout << myText[indexLast] << endl;
                cout << "Enter the number of paragraph after wich the range should be put :";
                cin >> indexPut;
                indexPut--;
                //cout << myText[indexPut] << endl;
                //system("pause");
                if (indexPut >= indexFirst && indexPut <= indexLast)
                {
                    throw "The range cannot be inserted inside itself!";
                }
            } while (indexFirst < 0 && indexFirst > myText.size() && indexLast < 0 && indexLast > myText.size() - 1);
            if (indexFirst > indexLast)
            {
                swap(indexFirst, indexLast);
            }
            vector<string>::const_iterator iter = myText.begin() + (indexPut + 1);
            if (iter < myText.begin() || iter > myText.end())
            {
                throw "Invalid PUT index. Put index is out of range";
            }
            myText.insert(iter, myText.begin() + indexFirst, myText.begin() + (indexLast + 1));
            //this->showText(0);
            //system("pause");
            if (indexPut >= indexLast)
            {
                myText.erase((myText.begin() + indexFirst), (myText.begin() + (indexLast + 1)));
            }
            else if (indexPut < indexFirst)
            {
                myText.erase(myText.begin() + (indexFirst + (indexLast - indexFirst + 1)), myText.begin() + (indexLast + (indexLast - indexFirst + 2)));
            }
        }
        else
        {
            throw "Too few elements in the vector to manipulate them!";
        }
    }

    /*+ знайти і замінити
    ( запитує зразок для пошуку
    ( запитує текст для заміни
    ( замінює усі входження зразка в усіх абзацах тексту*/

    void replaceText()
    {
        string search;
        string replace;
        cin.ignore();
        cout << "Type in text to find : ";
        getline(cin, search);
        cout << "Type in text to replace with : ";
        getline(cin, replace);
        for (int i = 0; i < myText.size(); ++i)
        {
            int k = myText[i].find(search);
            if (k >= 0)
            {
                myText[i].replace(k, search.length(), replace);
            }
        }
        cout << search << " was successfully replaced by " << replace << endl << endl;
        system("pause");
    }

    ~Editor();
};

void main()
{
    Editor *firstEditor = new Editor;
    int choice = 0;
    enum Menu
    {
        exit, create_file, open_file, save_file, clear_file, show_text, edit_paragraph, add_paragraph, replace_paragraphs, replace_text
    };
    do
    {
        do
        {
            system("cls");
            cout << "******************************" << endl
                << setw(17) << "MENU" << endl
                << "******************************" << endl
                << Menu::create_file << ". Create new file" << endl
                << "*****" << endl
                << Menu::open_file << ". Open file and read its content to vector" << endl
                << "*****" << endl
                << Menu::save_file << ". Save text to file" << endl
                << "*****" << endl
                << Menu::clear_file << ". Delete all text" << endl //зробив
                << "*****" << endl
                << Menu::show_text << ". Show the entire text" << endl //зробив
                << "*****" << endl
                << Menu::edit_paragraph << ". Edit single chosen paragraph" << endl
                << "*****" << endl
                << Menu::add_paragraph << ". Add new paragraph" << endl //зробив
                << "*****" << endl
                << Menu::replace_paragraphs << ". Replace range og Paragraphs" << endl
                << "*****" << endl
                << Menu::replace_text << ". Replace word/s in the text" << endl
                << "*****" << endl
                << "*****" << endl
                << Menu::exit << ". Exit" << endl << endl
                << "Make a choice : ";
            cin >> choice;
        } while (choice < Menu::exit && choice > Menu::replace_text);
        switch (choice)
        {
        case Menu::create_file:
        {
            firstEditor->createFile();
            break;
        }
        case Menu::open_file:
        {
            try
            {
                firstEditor->openFile();
            }
            catch (int i)
            {
                cerr << "Error " << i << " : Cannot open file for reading. Exiting...." << endl;
                system("pause");
            }
            break;
        }
        case Menu::save_file:
        {
            try
            {
                firstEditor->saveText();
            }
            catch (int m)
            {
                cerr << "Error " << m << " : Can't open file for writing. Exiting..." << endl;
                system("pause");
            }
            break;
        }
        case Menu::clear_file:
        {
            firstEditor->clearVector();
            break;
        }
        case Menu::show_text:
        {
            firstEditor->showText(0);
            break;
        }
        case Menu::edit_paragraph:
        {
            firstEditor->editParagraph();
            break;
        }
        case Menu::add_paragraph:
        {
            firstEditor->addParagraph();
            break;
        }
        case Menu::replace_paragraphs:
        {
            try
            {
                firstEditor->replaceParagraphs();
            }
            catch (string s)
            {
                cerr << "Replacing paragraphs error : " << s;
                system("pause");
            }
            break;
        }
        case Menu::replace_text:
        {
            firstEditor->replaceText();
            break;
        }
        case Menu::exit:
        {
            cout << "See you!!!" << endl;
            break;
        }
        default:
            break;
        }
    } while (choice != Menu::exit);
    system("pause");
}

42

(7 відповідей, залишених у C++)

за пам'ять дякую, а обробку помилок ми ще будемо вчити. Сподіваюсь нам там все детальніше пояснять.

43

(7 відповідей, залишених у C++)

Працюючий код:

#include<iostream>
#include <string>

using namespace std;

class Bracket
{
    struct Node
    {
        char bracket;
        Node *pNext;
    };
    int count;
    Node *pHead;

public:
    Bracket()
    {
        pHead = nullptr;
        count = 0;
    }

    Bracket(char obj)
    {
        Node *pCur = new Node;
        pCur->bracket = obj;
    }

    bool addBracket(char obj)
    {

        Node *pNew = new Node;
        if (pNew)
        {
            if (count == 0)
            {
                pHead = nullptr;
            }
            pNew->bracket = obj;
            pNew->pNext = pHead;
            pHead = pNew;
            count++;
            return true;
        }
        return false;
    }

    bool checkBrakets(char example)
    {
        if (count == 0 || pHead->bracket != example)
        {
            return false;
        }
        Node *pDel = new Node;
        pDel = pHead;
        pHead = pHead->pNext;
        delete pDel;
        pDel = nullptr;
        count--;
        return true;
    }
};

void main()
{
    string some_text;
    cout << "Enter your brackets : ";
    getline(cin, some_text);
    Bracket obj;
    for (int i = 0; i < some_text.length(); ++i)
    {
        if (some_text[i] == '(' || some_text[i] == '[' || some_text[i] == '{')
        {
            obj.addBracket(some_text[i]);
        }
        if (some_text[i] == ')' || some_text[i] == ']' || some_text[i] == '}')
        {
            char tmp;
            some_text[i] == ')' ? tmp = '(' : some_text[i] == ']' ? tmp = '[' : tmp = '{';
            if (obj.checkBrakets(tmp))
            {
                cout << "Brackets confirmed" << endl;
            }
            else
            {
                cout << "Brackets do not meet each other!" << endl;
                break;
            }
        }
    }
    system("pause");
}

44

(7 відповідей, залишених у C++)

чому ж не змінюється: 1. ноді pDel ми присвоюємо ноду pHead 2. pHead->pNext стає у вершину стеку 3. Видаляємо pDel і зменшуємо count. Оскільки працюємо з вказівниками, то разом з pDel видаляємо і колишню pHead.

Проблема в тому, що при створенні самого першого елементу стеку програма пропускає перевірку
if (pTail = nullptr)
            {
                pHead = pTail = pNew;
            }
і переходить. Блін, олень я. Треба робити перерви, бо сидіння за ПК цілими днями нідо чого хорошого не приводить, а лише до таких тупих помилок
+ деякі перевірки некоректні
важко

45

(7 відповідей, залишених у C++)

так от же ж:

bool checkBrakets(char example)
    {
        if (count == 0 || pHead->bracket != example)
        {
            return false;
        }
        Node *pDel = new Node;
        pDel = pHead;
        pHead = pHead->pNext;
        delete pDel;
        pDel = nullptr;
        count--;
        return true;
    }

але проблема в тому, що не кладеться

46

(7 відповідей, залишених у C++)

Привіт. В задачі потрібно перевірити чи співпадають відкриваючі та закриваючі дужки. Реалізацію задумав наступну: 1. вводимо строку; 2. проходимось циклом по кожному елементу строки 3. якщо знаходимо відкриваючу дужку - кладемо її в стек на початок 4. якщо дужка закриваюча - звіряємо її з тією, що у верхівці стеку; 5. якщо співпало - продовжуємо, ні - виходимо з циклу
Біда в тому, що у мене програма не кладе дужки в стек
В чому проблема?

#include<iostream>
#include <string>

using namespace std;

class Bracket
{
    struct Node
    {
        char bracket;
        Node *pNext;
    };
    int count;
    Node *pHead;
    Node *pTail;

public:
    Bracket()
    {
        pHead = pTail = nullptr;
        count = 0;
    }

    Bracket(char obj)
    {
        Node *pCur = new Node;
        pCur->bracket = obj;
    }

    bool addBracket(char obj)
    {

        Node *pNew = new Node;
        if (pNew)
        {
            if (count == 0)
            {
                pHead = pTail = nullptr;
            }
            pNew->bracket = obj;
            pNew->pNext = nullptr;
            if (pTail = nullptr)
            {
                pHead = pTail = pNew;
            }
            else if (pHead == pTail)
            {
                pHead->pNext = pNew;
                pTail = pNew;
            }
            else
            {
                pTail->pNext = pNew;
                pTail = pNew;
            }
            count++;
            return true;
        }
        return false;
    }

    bool checkBrakets(char example)
    {
        if (count == 0 || pHead->bracket != example)
        {
            return false;
        }
        Node *pDel = new Node;
        pDel = pHead;
        pHead = pHead->pNext;
        delete pDel;
        pDel = nullptr;
        count--;
        return true;
    }
};

void main()
{
    string some_text;
    cout << "Enter your brackets : ";
    getline(cin, some_text);
    Bracket obj;
    for (int i = 0; i < sizeof(some_text); ++i)
    {
        if (some_text[i] == '(' || some_text[i] == '[' || some_text[i] == '{')
        {
            obj.addBracket(some_text[i]);
        }
        if (some_text[i] == ')' || some_text[i] == ']' || some_text[i] == '}')
        {
            if (obj.checkBrakets(some_text[i]))
            {
                continue;;
            }
            else
            {
                cout << "Brackets do not meet each other!" << endl;
                break;
            }
        }
        cout << "Brackets confirmed" << endl;
    }
    system("pause");
}

47

(2 відповідей, залишених у C++)

Щоб це могло бути?

ахаха. Це моя перша програма з класами і це мали бути 2 конструктори, а вийшов 2 в 1. ахаха.

П.С. я Знайшов в чому помилка, але не можу зрозуміти чому так відбувається. Поясніть, будь ласка.
Проблема полягала у наступному:
У мене був код для видалення повідомлення ось такий :

for (Message *ptr = All, *dst = new_All; ptr < All + (size - 1); ++dst, ++ptr) 
{ 
if (ptr == All + index) 
{ 
++ptr; 
} 
*dst = *ptr; 

}
а треба було записати:

for (Message *ptr = All, *dst = new_All; ptr < All + (size - 1); ++dst, ++ptr) 
{ 
if (dst == All + index) 
{ 
++ptr; 
} 
*dst = *ptr; 
}

Зміна тут:
if (PTR == All + index) —-------------— if (DST== All + index)

Те саме відбувається і коли працювати з індексами:

for(int i = 0, j = 0, i < size - 1, ==i, ==j)
{
if(i == index) // умова починає працювати, якщо j == index
{
i++; // ++i однаково не працює
}
dst[j] = src[i]
}

Хтось розуміє, різницю логіки виконання цих кодів?

48

(4 відповідей, залишених у C++)

Ок. Дякую. Я власне так і думав, але толкового пояснення не міг знайти.

49

(4 відповідей, залишених у C++)

Ніби не зовсім так:
Деструктор в об’єктно-орієнтованому програмуванні — спеціальний метод класу, який викликається автоматично при знищенні об'єкта і призначений для його деініціалізації (наприклад звільнення пам'яті). https://uk.wikipedia.org/wiki/Деструкто … рамування)
І Дейтел пише, що деструктори автоматично викликаються для класів і створбвати їх не потрібно (перший зайшов - останній вийшов). Чи я щось не так розумію?

50

(4 відповідей, залишених у C++)

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<ctime>
#include <string>
#include <iomanip>
using namespace std;

class User
{
private:

};

class Admin
{
private:

};

class CoffeeBox
{
private:
    struct Coffee
    {
        string coffee_type;
        double coffee_price;
    };
    struct Adds
    {
        string add;
        double add_price;
    };
    int size_coffee;
    int size_adds;
    Coffee *c_types;
    Adds *a_types;
    double cash;
public:
    CoffeeBox()
    {
        size_coffee = 0;
        size_adds = 0;
        c_types = new Coffee[size_coffee];
        a_types = new Adds[size_adds];
        cash = 0;
    }

    CoffeeBox(string type_of_coffee, double c_price, string type_of_add, double a_price)
    {
        ++size_coffee;
        ++size_adds;
        c_types[size_coffee - 1].coffee_type = type_of_coffee;
        a_types[size_adds - 1].add = type_of_add;
        c_types[size_coffee - 1].coffee_price = c_price;
        a_types[size_adds - 1].add_price = a_price;
        cash = 0;
    }

    void show_adds()
    {
        cout << setw(15) << "\tNAME" << "PRICE" << endl;
        for (int i = 0; i < size_adds; i++)
        {
            cout << i + 1 << ". " << setw(12) << left << a_types[i].add << setw(5) << left << a_types[i].add_price<< endl;
        }
    }

    void show_coffees()
    {
        cout << setw(15) << "\tNAME" << "PRICE" << endl;
        for (int i = 0; i < size_adds; i++)
        {
            cout << i + 1 << ". " << setw(12) << left << c_types[i].coffee_type << setw(5) << left << c_types[i].coffee_price << endl;
        }
    }

    void add_coffee()
    {
        Coffee *new_coffee = new Coffee[size_coffee + 1];
        char choice;
        do
        {
            for (int i = 0; i < size_coffee; i++)
            {
                new_coffee[i] = c_types[i];
            }
            cout << "Enter the name of new coffee :";
            cin >> new_coffee[size_coffee + 1].coffee_type;
            cout << "Enter the price :";
            cin >> new_coffee[size_coffee + 1].coffee_price;
            size_coffee++;
            c_types = new_coffee;
            do
            {
                cout << "Add another coffee type? y/n :";
                cin >> choice;
            } while (choice != 'y' && choice != 'n');
        } while (choice != 'n');
    }

    double cash_operations(double sum)
    {

    }
};

У рядку 92 я роблю перепосилання основного масиву на копію (c_types = new_coffee;). В звичайних умовах я втрачав би пам'ять, але у класів є власні деструктори. Питання полягає в тому чи потрібно явно видаляти масив чи деструктор зробить свою роботу?
Дякую

Друзі, допоможіть. Створив клас Поштова скринька в яку я додаю повідомлення, виводжу їх на екран і видаляю.
Помітив наступну помилку: якщо додати 3 повідомлення (S1R1M1, S2R2M2, S3R3M3), потім видалити третє (2 по індексу), знову його додати, потім видалити перше (0 по індексу) і спробувати вивести повідомлення з індексом 1, то програма завершується з помилкою. Я так розумію, що щось десь виходить за межі масиву, але не розумію де.
Допоможіть розібратися. Усі маніпуляції проводив з Завданням 2! Ось код:

/*Розробіть клас Message, який моделює повідомлення електронної пошти.
Повідомлення містить одержувача, відправника, текст повідомлення, час створення.

Необхідні наступні функції-члени:
• конструктор, який приймає відправника і одержувача і встановлює часову відмітку (time stamp)
• Функція-член append, яка додає рядок тексту в тіло повідомлення
• Функція-член to_string, яка перетворює повідомлення в один довгий рядок, напр.: "From:

Harry Hacker\nTo: Rudolf Reindeer\n ..."
• Функція-член print, яка друкує текст повідомлення. Порада: Використовуйте to_string.

Для створення time stamp використайте функції і типи, визначені у ctime.h

Другий етап

Розробіть клас MessageBox, котрий моделює поштову скриньку.
Він повинен зберігати повідомлення у масиві (визначтеся, це має бути масив об'єктів, чи масив вказівників на об'єкти)

Реалізуйте наступні функції-члени:
Додавання нового повідомлення (void MessageBox::add_message(Message m);)
Повернути повідомлення по індексу (Message MessageBox::get_message(int i) const;)
Видалити повідомлення по індексу (void MessageBox::remove_message(int i);)
*/

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<ctime>
#include <string>
using namespace std;

#pragma region Task_1
class Message
{
    string sender;
    string receiver;
    time_t curr_time;
    string message_body;

public:
    Message()
    {

    }
    Message(const Message &obj)
    {
        sender = obj.sender;
        receiver = obj.receiver;
        curr_time = obj.curr_time;
        message_body = obj.message_body;
    }
    void add_message()
    {
        cout << "Enter e-mail of a sender : ";
        cin.ignore();
        getline(cin, sender);
        cout << "Enter e-mail of a receiver : ";
        getline(cin, receiver);
        append();
        curr_time = time(0);
    }

    //Функція-член append, яка додає рядок тексту в тіло повідомлення
    void append()
    {
        cout << "Type your message : " << endl;
        getline(cin, message_body);
    }

    //Функція-член to_string, яка перетворює повідомлення в один довгий рядок, напр.: "From: Harry Hacker\nTo: Rudolf Reindeer\n ..."

    string to_string()
    {

        string full = "From: " + sender + "\nTo: " + receiver + "\nMessage: " + message_body + "\nTime: " + ctime(&curr_time);
        return full;
    }

    //Функція-член print, яка друкує текст повідомлення. Порада: Використовуйте     to_string
    void print()
    {
        cout << to_string();
    }
};

void task1()
{
    Message *My = new Message();
    My->add_message();
    My->print();
    system("pause");
}
#pragma endregion

#pragma region Task_2

/*Другий етап

Розробіть клас MessageBox, котрий моделює поштову скриньку.
Він повинен зберігати повідомлення у масиві (визначтеся, це має бути масив об'єктів, чи масив вказівників на об'єкти)

Реалізуйте наступні функції-члени:
Додавання нового повідомлення (void MessageBox::add_message(Message m);)
Повернути повідомлення по індексу (Message MessageBox::get_message(int i) const;)
Видалити повідомлення по індексу (void MessageBox::remove_message(int i);)*/

class MessageBox
{
private:
    int size;
    Message *All;
public:

    MessageBox(int size)
    {
        size = 0;
        All = new Message[size];
    }

    //Додавання нового повідомлення (void MessageBox::add_message(Message m);)
#pragma region Add_Message
private:
    //void get_message_from_user(Message &single)
    //{
    //    single.add_message();
    //}

    void move_class(Message *dst)
    {
        for (Message *src_ptr = All, *dst_ptr = dst; src_ptr < All + size; ++dst_ptr, ++src_ptr)
        {
            *dst_ptr = *src_ptr;
        }
    }

    Message* AddClass()
    {
        int newSize = size + 1;
        Message *new_box = new Message[newSize];
        move_class(new_box);
        (new_box + newSize - 1)->add_message();
        //get_message_from_user(*(new_box + newSize - 1));

        size = newSize;
        delete[] All;
        All = NULL;
        return new_box;
    }

public:
    void add_message()
    {
        char YesOrNot;
        do
        {
            All = AddClass();
            cout << "Object added" << endl;
            do
            {
                cout << "Add another object? (y/n): ";
                cin >> YesOrNot;
            } while (YesOrNot != 'y' && YesOrNot != 'n');
        } while (YesOrNot != 'n');
    }
#pragma endregion

    //Повернути повідомлення по індексу (Message MessageBox::get_message(int i) const;)
#pragma region Show_message
private:
    bool check_index(const int index)
    {
        bool is_in = false;
        if (index >= 0 && index < size)
        {
            is_in = true;
        }
        return is_in;
    }
public:
    void show_message()
    {
        int index;
        char YesOrNo;
        do
        {
            cout << "Enter the index of a message to show : ";
            cin >> index;
            if (check_index(index))
            {
                (All + index)->print();
            }
            else
            {
                cout << endl << "***** Invalid index! *****" << endl << endl;
            }
            do
            {
                cout << "Show another message? (y/n): ";
                cin >> YesOrNo;
            } while (YesOrNo != 'y' && YesOrNo != 'n');
        } while (YesOrNo != 'n');
    }
#pragma endregion

    //Видалити повідомлення по індексу (void MessageBox::remove_message(int i);)
#pragma region Delete_message
private:
    Message *delete_1_message(const int index)
    {
        int new_size = size - 1;
        Message *new_All = new Message[new_size];
        for (Message *ptr = All, *dst = new_All; ptr < All + (size - 1); ++dst, ++ptr)
        {
            if (ptr == All + index)
            {
                ++ptr;
            }
            *dst = *ptr;
        }

        size = new_size;
        if (All != nullptr)
        {
            delete[] All;
            All = NULL;
        }
        return new_All;
    }
public:
    void delete_messages()
    {
        int index;
        char YesOrNo;
        do
        {
            cout << "Enter the index of a message to delete : ";
            cin >> index;
            if (check_index(index))
            {
                All = delete_1_message(index);
                cout << endl << "***** Message deleted *****" << endl << endl;
            }
            else
            {
                cout << endl << "***** Invalid index! *****" << endl << endl;
            }
            do
            {
                cout << "Delete another message? (y/n): ";
                cin >> YesOrNo;
            } while (YesOrNo != 'y' && YesOrNo != 'n');
        } while (YesOrNo != 'n');
    }
#pragma endregion
};

void task2()
{
    int size = 0;
    MessageBox box = MessageBox(size);
    enum Menu
    {
        exit, add, show, remove
    };
    int choice = 0;
    do
    {
        do
        {
            cout << "Choose action :" << endl
                << Menu::add << ". Add message to the box" << endl
                << Menu::show << ". Show message by index" << endl
                << Menu::remove << ". Delete message by index" << endl
                << Menu::exit << ". Exit" << endl << endl
                << "Make a choice : ";
            cin >> choice;
        } while (choice < Menu::exit && choice > Menu::remove);
        switch (choice)
        {
        case Menu::add: box.add_message();
            break;
        case Menu::show: box.show_message();
            break;
        case Menu::remove: box.delete_messages();
            break;
        case Menu::exit: cout << "Good bye!" << endl;
        default:
            break;
        }
    } while (choice != Menu::exit);
}
#pragma endregion 

void main()
{
    enum Menu
    {
        exit, t1, t2
    };
    int choice = 0;
    do
    {
        do
        {
            cout << "Choose action :" << endl
                << Menu::t1 << ". Task 1. Message" << endl
                << Menu::t2 << ". Task 2. Message box" << endl
                << Menu::exit << ". Exit" << endl << endl
                << "Make a choice : ";
            cin >> choice;
        } while (choice < Menu::exit && choice > Menu::t2);
        switch (choice)
        {
        case Menu::t1: task1();
            break;
        case Menu::t2: task2();
            break;
        case Menu::exit: cout << "Good bye!" << endl;
            break;
        default:
            break;
        }
    } while (choice != Menu::exit);
    system("pause");
}

52

(14 відповідей, залишених у C++)

Прогу написав. Все пофіксив. Все працює. Варто викладати код? Чи нехай майбутні програмери самі доходять?

53

(19 відповідей, залишених у C++)

Та все ж виклади, бо цікаво про які прямокутники йшла мова ;)

54

(14 відповідей, залишених у C++)

if (YesOrNot = 'n') помітив і виправив

Нащо ви звільняєте пам'ять за посиланням new_source? Ви ж це посилання далі повертаєте.

Я повертаю return source;

Все працює. Дякую. Тепер проблема з записом файлу. ахаха. Іду спати, мабуть

55

(14 відповідей, залишених у C++)

Пишу в Студії 2013. Ось результат компіляції:
1>------ Сборка начата: проект: Проект4, Конфигурация: Debug Win32 ------
1>  Исходный код.cpp
1>  Проект4.vcxproj -> C:\Users\Serg\Documents\Visual Studio 2013\Projects\Проект4\Debug\Проект4.exe
========== Сборка: успешно: 1, с ошибками: 0, без изменений: 0, пропущено: 0 ==========

Виправив те, що показали, окрім 234 (змінив код) і так і не зрозумів про що йдеться. Можете ще раз проглянути

/*Предметна область - бібліотека.
Розв'язувані задачі: видача довідок про наявність книг, журналів, газет. Реалізувати наступні сервіси:
Заповнення бази даних
Перегляд даних про всі джерела
Доповнення бази даних записом джерела
Видалення джерела із бази даних
Упорядкування по полях: тип інформаційного джерела (книга, журнал, газета) і назва
Пошук: наявність заданої книги (відомі автор і назва), наявність заданого журналу
Вибірка: книги автора ХХ; книги певної категорії (фантастика, детектив тощо), журнали за певний рік (відомі рік і назва журналу)
Обчислення: кількість книг деякої категорії
Корекція: видалення зведень про газети за певний рік
Табличний звіт: список боржників книг певного автора
Для обробки даних скористатися динамічним масивом покажчиків на структури відповідного типу.
*/

#include <ctime>
#include <iomanip>
#include <iostream>
#include <string>
#include <fstream>
#include<windows.h>

using namespace std;

struct Date
{
    int day;
    int month;
    int year;
};
struct Item
{
    int serial_number;
    string source_type;
    string name;
    string author;
    int year;
    string genre;
    string publisher;
    string is_given;
};

#pragma region Show_library
//Вивід бібліотеки на екран
void print_source(Item *source)
{
    cout << setw(17) << "Serial number" << " :   " << source->serial_number << endl
        << setw(17) << left << "Type" << " :   " << source->source_type << endl
        << setw(17) << left << "Name" << " :   " << source->name << endl
        << setw(17) << left << "Author" << " :   " << source->author << endl
        << setw(17) << left << "Date" << " :   " << source->year << endl
        << setw(17) << left << "Genre" << " :   " << source->genre << endl
        << setw(17) << left << "Publiher" << " :   " << source->publisher << endl
        << setw(17) << left << "Given to" << " :   " << source->is_given << endl
        << "--------------------------------------------------------------------------------" << endl;
}

void print_sources(Item *sources, const int quantity)
{
    //cout << setw(20) << "Book name" << setw(20) << "Author" << setw(15) << "Publisher" << setw(15) << "Genre" << endl;
    cout << "List of sources" << endl << endl;
    for (Item *ptr = sources; ptr < sources + quantity; ++ptr)
    {
        print_source(ptr);
    }
}
#pragma endregion

#pragma region Save_file
void save_file(Item *sources, const int file_size)
{
    char confirm;
    system("cls");
    do
    {
        cout << "Are you sure you want to save changes? y/n : ";
        cin >> confirm;
    } while (confirm != 'y' && confirm != 'n');
    if (confirm == 'y')
    {
        string outFileName = "Library.txt";
        ofstream outFile;
        outFile.open(outFileName, ios_base::out);
        if (!outFile.is_open())
        {
            cout << "Can't open " << outFileName << " for writing. Exiting..." << endl;
            system("pause");
            exit(1);
        }
        outFile << file_size;
        for (Item *ptr = sources; ptr < sources + file_size; ++ptr)
        {
            outFile << endl
                << ptr->serial_number << ";"
                << ptr->source_type << ";"
                << ptr->name << ";"
                << ptr->author << ";"
                << ptr->year << ";"
                << ptr->genre << ";"
                << ptr->publisher << ";"
                << ptr->is_given << ";";
        }
        outFile.close();
        cout << endl << "File saved" << endl << endl;
    }
    else
    {
        cout << endl << "Changes declined" << endl << endl;
    }
}
#pragma endregion

#pragma region Add_source
//заповнення бібліотеки користувачем
void get_sources_from_user(Item *source, int index)
{
    source->serial_number = index;
    int type = 0;
    do
    {
        cout << "Choose source type :" << endl
            << "1. Book" << endl
            << "2. Magazine" << endl
            << "3. News paper" << endl << endl
            << "Make a choice : ";
        cin >> type;
    } while (type < 1 || type > 3);
    switch (type)
    {
    case 1: source->source_type = "book";
        break;
    case 2: source->source_type = "magazine";
        break;
    case 3: source->source_type = "news paper";
        break;
    default:
        cout << "Wrong choice!" << endl;
        break;
    }
    cin.ignore();
    //cout << "Enter source type (book, magazine, news paper) : ";
    //getline(cin, source->source_type);
    cout << "Type the name of a source : ";
    getline(cin, source->name);
    cout << "Type the author of a source : ";
    getline(cin, source->author);
    cin >> source->year;
    //bool correct = false;
    //do
    //{
    //    cout << "Type the date of a source (01 12 2016) : ";
    //    cin >> sources[i].date.day >> sources[i].date.month >> sources[i].date.year;
    //    if (sources[i].date.day < 1 || sources[i].date.day > 31)
    //    {
    //        sources[i].date.day = NULL;
    //        correct = true;
    //    }
    //    else if (sources[i].date.month < 1 || sources[i].date.month > 12)
    //    {
    //        sources[i].date.month = NULL;
    //        correct = true;
    //    }
    //    else if (sources[i].date.year > 2016)
    //    {
    //        cout << "You've entered invalid year" << endl;
    //        correct = false;
    //    }
    //    else
    //    {
    //        correct = true;
    //    }
    //} while (correct != true);
    cout << "Type the publisher of a source : ";
    getline(cin, source->publisher);
    cout << "Type the genre of a source : ";
    getline(cin, source->genre);
    source->is_given = "no information";
}

void move_source(Item *src, const int count, Item *dst)
{
    for (Item *src_ptr = src, *dst_ptr = dst; src_ptr < src + count; ++dst_ptr, ++src_ptr)
    {
        //*dst_ptr = *src_ptr;
        //src_ptr = nullptr;
        dst_ptr->serial_number = src_ptr->serial_number;
        dst_ptr->source_type = src_ptr->source_type;
        dst_ptr->name = src_ptr->name;
        dst_ptr->author = src_ptr->author;
        dst_ptr->year = src_ptr->year;
        dst_ptr->genre = src_ptr->genre;
        dst_ptr->publisher = src_ptr->publisher;
        dst_ptr->is_given = src_ptr->is_given;
    }
}

Item* AddStruct(Item* source, int *file_size)
{
    int newSize = *file_size + 1;
    if (*file_size == 0)
    {
        source = new Item[newSize]; // виділення пам'яті для першої структури
    }
    else
    {
        Item *new_source = new Item[newSize];
        move_source(source, *file_size, new_source);
        print_sources(new_source, newSize);
        get_sources_from_user((new_source + newSize), newSize);

        delete[] source;
        source = new_source;
        delete[] new_source;
    }
    *file_size = newSize;
    return source;
}

void add_source(Item *sources, int file_size)
{
    char YesOrNot;
    do
    {
        sources = AddStruct(sources, &file_size);

        file_size++;
        do
        {
            cout << "Add onather source? (y/n): ";
            cin >> YesOrNot;
            cin.get();
        } while (YesOrNot != 'y' || YesOrNot != 'n');
        if (YesOrNot = 'n')
        {
            save_file(sources, file_size);
        }
    } while (YesOrNot != 'n');

    print_source(sources + file_size);

}
#pragma endregion

#pragma region Edit_source
//Редагування
void edit_book(Item *sources, const int quantity)
{
    system("cls");
    print_sources(sources, quantity);
    int choice;
    enum parameters
    {
        Exit,
        source_type,
        name,
        author,
        year,
        genre,
        publisher
    };

    do
    {
        cout << "Enter the number of book to edit : ";
        cin >> choice;
    } while (choice < 1 || choice > quantity);
    choice -= 1;

    int choice_parameter;
    do
    {
        cout << "You are about to edit " << sources[choice].name << endl << endl
            << source_type << ". Source type" << endl
            << name << ". Name" << endl
            << author << ". Author" << endl
            << year << ". Year of publication" << endl
            << genre << ". Genre" << endl
            << publisher << ". Publisher" << endl
            << Exit << ". Exit" << endl << endl;
        do
        {
            cout << "Enter the parameter to edit : ";
            cin >> choice_parameter;
        } while (choice_parameter < 0 || choice_parameter > 6);

        cin.ignore();
        switch (choice_parameter)
        {
        case parameters::source_type:
        {
            int type = 0;
            do
            {
                cout << "Choose a source type :" << endl
                    << "1. Book" << endl
                    << "2. Magazine" << endl
                    << "3. News paper" << endl << endl
                    << "Make a choice : ";
                cin >> type;
            } while (type < 1 || type > 3);
            switch (type)
            {
            case 1: (sources + choice)->source_type = "book";
                break;
            case 2: (sources + choice)->source_type = "magazine";
                break;
            case 3: (sources + choice)->source_type = "news paper";
                break;
            default:
                cout << "Wrong choice!" << endl;
                break;
            }
        }
        break;
        case parameters::name:
        {
            cout << "Enter new name of the book : ";
            getline(cin, sources[choice].name);
        }
        break;
        case parameters::author:
            cout << "Enter new author of the book : ";
            getline(cin, sources[choice].author);
            break;
        case parameters::year:
            cout << "Enter new year of publication : ";
            cin >> sources[choice].year;
            break;
        case parameters::genre:
            cout << "Enter new genre of the book : ";
            getline(cin, sources[choice].genre);
            break;
        case parameters::publisher:
            cout << "Enter new publisher of the book : ";
            getline(cin, sources[choice].publisher);
            break;

        case parameters::Exit:
            cout << "Good bye!" << endl;
        default:
            break;
        }
        cout << endl << "Edited source :" << endl;
        print_source(sources + choice);
    } while (choice_parameter != 0);
    save_file(sources, quantity);
}
#pragma endregion

#pragma region Sorting
//Сортировка массива по названию книг
void sort_by_name(Item *sources, const int quantity)
{
    for (int i = 0; i < quantity; ++i)
    {
        for (int j = 0; j < quantity - 1 - i; ++j)
        {
            if (sources[j].name > sources[j + 1].name)
            {
                swap(sources[j], sources[j + 1]);
            }
        }
    }
}

//Сортировка массива по автору
void sort_by_author(Item *sources, const int quantity)
{
    for (int i = 0; i < quantity; ++i)
    {
        for (int j = 0; j < quantity - 1 - i; ++j)
        {
            if (sources[j].author > sources[j + 1].author)
            {
                swap(sources[j], sources[j + 1]);
            }
        }
    }
}

//Сортировка массива по издательству
void sort_by_publisher(Item *sources, const int quantity)
{
    for (int i = 0; i < quantity; ++i)
    {
        for (int j = 0; j < quantity - 1 - i; ++j)
        {
            if (sources[j].publisher > sources[j + 1].publisher)
            {
                swap(sources[j], sources[j + 1]);
            }
        }
    }
}

//Сортировка массива по типу
void sort_by_source_type(Item *sources, const int quantity)
{
    for (int i = 0; i < quantity; ++i)
    {
        for (int j = 0; j < quantity - 1 - i; ++j)
        {
            if (sources[j].source_type > sources[j + 1].source_type)
            {
                swap(sources[j], sources[j + 1]);
            }
        }
    }
}

//Сортировка массива по году
void sort_by_year(Item *sources, const int quantity)
{
    for (int i = 0; i < quantity; ++i)
    {
        for (int j = 0; j < quantity - 1 - i; ++j)
        {
            if (sources[j].year > sources[j + 1].year)
            {
                swap(sources[j], sources[j + 1]);
            }
        }
    }
}

//Сортировка массива по жанру
void sort_by_genre(Item *sources, const int quantity)
{
    for (int i = 0; i < quantity; ++i)
    {
        for (int j = 0; j < quantity - 1 - i; ++j)
        {
            if (sources[j].genre > sources[j + 1].genre)
            {
                swap(sources[j], sources[j + 1]);
            }
        }
    }
}

//меню сортування книг
void sort_sources(Item *sources, const int quantity)
{
    enum Sorting
    {
        exit, source_type, name, author, year, genre, publisher
    };
    int choice;
    do
    {
        do
        {
            cout << "Sort sources by :" << endl
                << source_type << ". Type of source" << endl
                << name << ". Name" << endl
                << author << ". Author" << endl
                << year << ". Year" << endl
                << genre << ". Genre" << endl
                << publisher << ". Publisher" << endl
                << exit << ". Exit" << endl << endl
                << "Enter the parameter : ";
            cin >> choice;
        } while (choice < exit || choice > publisher);
        switch (choice)
        {
        case source_type: sort_by_source_type(sources, quantity);
            break;
        case name: sort_by_name(sources, quantity);
            break;
        case author: sort_by_author(sources, quantity);
            break;
        case year: sort_by_year(sources, quantity);
            break;
        case genre: sort_by_genre(sources, quantity);
            break;
        case publisher: sort_by_publisher(sources, quantity);
            break;
        case 0: cout << "Thanks!" << endl;
            break;
        default:
            break;
        }
        system("cls");
        cout << "Sorted ";
        print_sources(sources, quantity);
    } while (choice != 0);
}
#pragma endregion

#pragma region Find_source
//Поиск книг по автору
void search_by_author(Item *sources, const int quantity) // Можна шукати як по прізвищу так і по імені
{
    int counter = 0;
    cin.ignore();
    string search_word;
    cout << "Enter author's name : ";
    getline(cin, search_word);
    bool is_in = false;
    for (int i = 0; i < quantity; ++i)
    {
        int k = -1;
        k = sources[i].author.find(search_word);
        if (k >= 0)
        {
            is_in = true;
            cout << "--------------------------------------------------------------------------------" << endl;
            print_source(sources + i);
            ++counter;
        }
    }
    if (is_in == false)
    {
        cout << "No match found." << endl;
    }
    else
    {
        cout << endl << counter << "sources found" << endl << endl << endl;
    }
}

//Поиск книги по названию
void search_by_name(Item *sources, const int quantity) // Можна шукати по будь-якому слові в назві
{
    int counter = 0;
    cin.ignore();
    string search_word;
    cout << "Enter the name of book: ";
    getline(cin, search_word);
    bool is_in = false;
    for (int i = 0; i < quantity; ++i)
    {
        int k = -1;
        k = sources[i].name.find(search_word);
        if (k >= 0)
        {
            is_in = true;
            cout << "--------------------------------------------------------------------------------" << endl;
            print_source(sources + i);
            ++counter;
        }
    }
    if (is_in == false)
    {
        cout << "--------------------------------------------------------------------------------" << endl
            << "No match found." << endl << endl
            << "--------------------------------------------------------------------------------" << endl;
    }
    else
    {
        cout << endl << counter << "sources found" << endl << endl << endl;
    }
}

void search_by_publisher(Item *sources, const int quantity) // Можна шукати по будь-якому слові в назві
{
    int counter = 0;
    cin.ignore();
    string search_word;
    cout << "Enter the publisher of sources : ";
    getline(cin, search_word);
    bool is_in = false;
    for (int i = 0; i < quantity; ++i)
    {
        int k = -1;
        k = sources[i].publisher.find(search_word);
        if (k >= 0)
        {
            is_in = true;
            cout << "--------------------------------------------------------------------------------" << endl;
            print_source(sources + i);
            ++counter;
        }
    }
    if (is_in == false)
    {
        cout << "--------------------------------------------------------------------------------" << endl
            << "No match found." << endl << endl
            << "--------------------------------------------------------------------------------" << endl;
    }
    else
    {
        cout << endl << counter << "sources found" << endl << endl << endl;
    }
}

void search_book(Item *sources, const int quantity)
{
    int choice;
    do
    {
        do
        {
            cout << "Search book by :" << endl
                << "1. Name" << endl
                << "2. Author" << endl
                << "3. Publisher" << endl
                << "0. Exit" << endl << endl
                << "Enter the parameter : ";
            cin >> choice;
        } while (choice < 0 || choice > 3);

        switch (choice)
        {
        case 1: search_by_name(sources, quantity);
            break;
        case 2: search_by_author(sources, quantity);
            break;
        case 3: search_by_publisher(sources, quantity);
            break;
        case 0: cout << "Thanks!" << endl;
            break;
        default:
            break;
        }
    } while (choice != 0);
}

void search_magazine(Item *sources, const int quantity)
{
    string name;
    cout << "Enter the name of magazine or news paper : ";
    cin.ignore();
    getline(cin, name);
    int year;
    cout << "Enter the year of magazine or news paper : ";
    cin >> year;
    bool is_in = false;
    for (Item *ptr = sources; ptr < sources + quantity; ++ptr)
    {
        int k = -1;
        k = ptr->name.find(name);
        if (k >= 0)
        {
            if (ptr->year == year)
            {
                is_in = true;
                cout << "--------------------------------------------------------------------------------" << endl;
                print_source(ptr);
                break;
            }
        }
    }
    if (is_in == false)
    {
        cout << "--------------------------------------------------------------------------------" << endl
        << "No match found." << endl << endl
        << "--------------------------------------------------------------------------------" << endl;
    }
}

void search_source(Item *sources, const int quantity)
{
    enum Variants
    {
        exit, book, magazine
    };
    int choice = 0;
    do
    {
        do
        {
            cout << "Choose what do you want to find :" << endl
                << book << ". Book" << endl
                << magazine << ". Magazine or News paper" << endl
                << exit << ". Cancel" << endl
                << "Your choice : ";
            cin >> choice;
        } while (choice < exit || choice > magazine);
        switch (choice)
        {
        case book: search_book(sources, quantity);
            break;
        case magazine: search_magazine(sources, quantity);
            break;
        case exit: cout << "CANCELED" << endl;
            break;;
        default:
            break;
        }
    } while (choice != exit);
}
#pragma endregion

/*void create_array(ifstream *read_file, int lib_size, Item *sources)
{
    string item_param;
    int i = 0;
    while (!read_file.eof())
    {
    cout << i << endl;
    getline(read_file, item_param, ';');
    sources[i].source_type = item_param;

    getline(read_file, item_param, ';');
    sources[i].name = item_param;
    cout << sources[i].name << endl;

    getline(read_file, item_param, ';');
    sources[i].author = item_param;

    getline(read_file, item_param, ';');
    sources[i].year = atoi(item_param.c_str()); //i = atoi(string_name.c_str());

    getline(read_file, item_param, ';');
    sources[i].genre = item_param;

    getline(read_file, item_param, ';');
    sources[i].publisher = item_param;

    getline(read_file, item_param, ';');
    sources[i].is_given = item_param;

    i++;
    read_file.seekg(2, ios::cur);
    }
}*/

int get_sources_quantity(ifstream read_file)
{
    int quant = 0;
    string number;
    read_file >> number;
    quant = atoi(number.c_str());
    return quant;
}

int get_position(int lib_size)
{
    int counter = 0;
    if (lib_size <= 0)
    {
        counter = 0;
    }
    else if (lib_size < 10)
    {
        counter = 1;
    }
    else
    {
        do
        {
            lib_size /= 10;
            ++counter;
        } while (lib_size >= 1);
    }
    return counter;
}

void main()
{

    ifstream read_file;
    string read_file_name = "Library.txt";

    read_file.open(read_file_name, ios_base::in);
    if (!read_file.is_open())
    {
        cerr << "Cannot open " << read_file_name << " for reading. Exiting...." << endl;
        system("pause");
        exit(1);
    }

    int lib_size = 0;
    string number;
    read_file >> number;
    lib_size = atoi(number.c_str());
    cout << "Library consists of " << lib_size << " sources" << endl << endl;
    Item *sources = new Item[lib_size];
    string item_param;
    int i = 0;
    int position = get_position(lib_size);
    read_file.seekg(position + 2);

    for (; i < lib_size; ++i)
    {
        getline(read_file, item_param, ';');
        sources[i].serial_number = atoi(item_param.c_str());

        getline(read_file, item_param, ';');
        sources[i].source_type = item_param;

        getline(read_file, item_param, ';');
        sources[i].name = item_param;

        getline(read_file, item_param, ';');
        sources[i].author = item_param;

        getline(read_file, item_param, ';');
        sources[i].year = atoi(item_param.c_str()); //i = atoi(string_name.c_str());

        getline(read_file, item_param, ';');
        sources[i].genre = item_param;

        getline(read_file, item_param, ';');
        sources[i].publisher = item_param;

        getline(read_file, item_param, ';');
        sources[i].is_given = item_param;

        read_file.seekg(2, ios::cur);
    }

    int choice;
    enum menu
    {
        Exit,
        Add,
        Print,
        Edit,
        Sort,
        Search
    };

    do
    {
        do
        {
            cout << Add << ". Add source" << endl
                << Print << ". Print sources" << endl
                << Edit << ". Edit sources" << endl
                << Sort << ". Sort sources" << endl
                << Search << ". Search source" << endl
                << Exit << ". Exit" << endl << endl
                << "Enter the action : ";
            cin >> choice;
        } while (choice < 0 || choice > 5);
        switch (choice)
        {
        case menu::Add: add_source(sources, lib_size);
            break;
        case menu::Print:
            print_sources(sources, lib_size);
            break;
        case menu::Edit:
            edit_book(sources, lib_size);
            break;
        case menu::Sort:
            sort_sources(sources, lib_size);
            break;
        case menu::Search:
            search_source(sources, lib_size);
            break;
        case menu::Exit:
            cout << "Good bye!" << endl;
        default:
            break;
        }
    } while (choice != 0);

    delete[] sources;
    system("pause");
}

56

(14 відповідей, залишених у C++)

koala написав:

Можете змінений код ще раз викласти?

У вкладеному файлі є. Але і в повідомлення вставлю
Цікавить частина в "#pragma region Add_source"

#include <ctime>
#include <iomanip>
#include <iostream>
#include <string>
#include <fstream>
#include<windows.h>

using namespace std;

struct Date
{
    int day;
    int month;
    int year;
};
struct Item
{
    int serial_number;
    string source_type;
    string name;
    string author;
    int year;
    string genre;
    string publisher;
    string is_given;
};

#pragma region Show_library
//Вивід бібліотеки на екран
void print_source(Item *source)
{
    cout << setw(17) << "Serial number" << " :   " << source->serial_number << endl
        << setw(17) << left << "Type" << " :   " << source->source_type << endl
        << setw(17) << left << "Name" << " :   " << source->name << endl
        << setw(17) << left << "Author" << " :   " << source->author << endl
        << setw(17) << left << "Date" << " :   " << source->year << endl
        << setw(17) << left << "Genre" << " :   " << source->genre << endl
        << setw(17) << left << "Publiher" << " :   " << source->publisher << endl
        << setw(17) << left << "Given to" << " :   " << source->is_given << endl
        << "--------------------------------------------------------------------------------" << endl;
}

void print_sources(Item *sources, const int quantity)
{
    //cout << setw(20) << "Book name" << setw(20) << "Author" << setw(15) << "Publisher" << setw(15) << "Genre" << endl;
    cout << "List of sources" << endl << endl;
    for (Item *ptr = sources; ptr < sources + quantity; ++ptr)
    {
        print_source(ptr);
    }
}
#pragma endregion

#pragma region Save_file
void save_file(Item *sources, const int file_size)
{
    char confirm;
    system("cls");
    do
    {
        cout << "Are you sure you want to save changes? y/n : ";
        cin >> confirm;
    } while (confirm != 'y' && confirm != 'n');
    if (confirm == 'y')
    {
        string outFileName = "Library.txt";
        ofstream outFile;
        outFile.open(outFileName, ios_base::out);
        if (!outFile.is_open())
        {
            cout << "Can't open " << outFileName << " for writing. Exiting..." << endl;
            system("pause");
            exit(1);
        }
        int counter = 0;
        outFile << file_size;
        for (Item *ptr = sources; ptr < sources + file_size; ++ptr)
        {
            outFile << endl
                << ptr->serial_number << ";"
                << ptr->source_type << ";"
                << ptr->name << ";"
                << ptr->author << ";"
                << ptr->year << ";"
                << ptr->genre << ";"
                << ptr->publisher << ";"
                << ptr->is_given << ";";
        }
        outFile.close();
        cout << endl << "File saved" << endl << endl;
    }
    else
    {
        cout << endl << "Changes declined" << endl << endl;
    }
}
#pragma endregion

#pragma region Add_source
//заповнення бібліотеки користувачем
void get_sources_from_user(Item *source, int index)
{
    source->serial_number = index;
    int type = 0;
    do
    {
        cout << "Choose source type :" << endl
            << "1. Book" << endl
            << "2. Magazine" << endl
            << "3. News paper" << endl << endl
            << "Make a choice : ";
        cin >> type;
    } while (type < 1 || type > 3);
    switch (type)
    {
    case 1: source->source_type = "book";
        break;
    case 2: source->source_type = "magazine";
        break;
    case 3: source->source_type = "news paper";
        break;
    default:
        cout << "Wrong choice!" << endl;
        break;
    }
    cin.ignore();
    cout << "Type the name of a source : ";
    getline(cin, source->name);
    cout << "Type the author of a source : ";
    getline(cin, source->author);
    cin >> source->year;
    cout << "Type the publisher of a source : ";
    getline(cin, source->publisher);
    cout << "Type the genre of a source : ";
    getline(cin, source->genre);
    source->is_given = "no information";
}

void move_source(Item *src, const int count, Item *dst)
{
    for (Item *src_ptr = src, *dst_ptr = dst; src_ptr < src + count; ++dst_ptr, ++src_ptr)
    {
        //*dst_ptr = *src_ptr;
        //src_ptr = nullptr;
        dst_ptr->serial_number = src_ptr->serial_number;
        dst_ptr->source_type = src_ptr->source_type;
        dst_ptr->name = src_ptr->name;
        dst_ptr->author = src_ptr->author;
        dst_ptr->year = src_ptr->year;
        dst_ptr->genre = src_ptr->genre;
        dst_ptr->publisher = src_ptr->publisher;
        dst_ptr->is_given = src_ptr->is_given;
    }
}

Item* AddStruct(Item* source, int *file_size)
{
    int newSize = *file_size + 1;
    if (*file_size == 0)
    {
        source = new Item[newSize]; // виділення пам'яті для першої структури
    }
    else
    {
        Item *new_source = new Item[newSize];
        move_source(source, *file_size, new_source);
        print_sources(new_source, newSize);
        get_sources_from_user((new_source + newSize), newSize);

        delete[] source;
        source = new_source;
        delete[] new_source;
    }
    *file_size = newSize;
    return source;
}

void add_source(Item *sources, int file_size)
{
    char YesOrNot;
    do
    {
        sources = AddStruct(sources, &file_size);

        file_size++;
        do
        {
            cout << "Add onather source? (y/n): ";
            cin >> YesOrNot;
            cin.get();
        } while (YesOrNot != 'y' || YesOrNot != 'n');
        if (YesOrNot = 'n')
        {
            save_file(sources, file_size);
        }
    } while (YesOrNot != 'n');

    print_source(sources + file_size);

}
#pragma endregion

#pragma region Edit_source
//Редагування
void edit_book(Item *sources, const int quantity)
{
    system("cls");
    print_sources(sources, quantity);
    int choice;
    enum parameters
    {
        Exit,
        source_type,
        name,
        author,
        year,
        genre,
        publisher
    };

    do
    {
        cout << "Enter the number of book to edit : ";
        cin >> choice;
    } while (choice < 1 || choice > quantity);
    choice -= 1;

    int choice_parameter;
    do
    {
        cout << "You are about to edit " << sources[choice].name << endl << endl
            << source_type << ". Source type" << endl
            << name << ". Name" << endl
            << author << ". Author" << endl
            << year << ". Year of publication" << endl
            << genre << ". Genre" << endl
            << publisher << ". Publisher" << endl
            << Exit << ". Exit" << endl << endl;
        do
        {
            cout << "Enter the parameter to edit : ";
            cin >> choice_parameter;
        } while (choice_parameter < 0 || choice_parameter > 6);

        cin.ignore();
        switch (choice_parameter)
        {
        case parameters::source_type:
        {
            int type = 0;
            do
            {
                cout << "Choose a source type :" << endl
                    << "1. Book" << endl
                    << "2. Magazine" << endl
                    << "3. News paper" << endl << endl
                    << "Make a choice : ";
                cin >> type;
            } while (type < 1 || type > 3);
            switch (type)
            {
            case 1: (sources + choice)->source_type = "book";
                break;
            case 2: (sources + choice)->source_type = "magazine";
                break;
            case 3: (sources + choice)->source_type = "news paper";
                break;
            default:
                cout << "Wrong choice!" << endl;
                break;
            }
        }
        break;
        case parameters::name:
        {
            cout << "Enter new name of the book : ";
            getline(cin, sources[choice].name);
        }
        break;
        case parameters::author:
            cout << "Enter new author of the book : ";
            getline(cin, sources[choice].author);
            break;
        case parameters::year:
            cout << "Enter new year of publication : ";
            cin >> sources[choice].year;
            break;
        case parameters::genre:
            cout << "Enter new genre of the book : ";
            getline(cin, sources[choice].genre);
            break;
        case parameters::publisher:
            cout << "Enter new publisher of the book : ";
            getline(cin, sources[choice].publisher);
            break;

        case parameters::Exit:
            cout << "Good bye!" << endl;
        default:
            break;
        }
        cout << endl << "Edited source :" << endl;
        print_source(sources + choice);
    } while (choice_parameter != 0);
    save_file(sources, quantity);
}
#pragma endregion

#pragma region Sorting
//Сортировка массива по названию книг
void sort_by_name(Item *sources, const int quantity)
{
    for (int i = 0; i < quantity; ++i)
    {
        for (int j = 0; j < quantity - 1 - i; ++j)
        {
            if (sources[j].name > sources[j + 1].name)
            {
                swap(sources[j], sources[j + 1]);
            }
        }
    }
}

//Сортировка массива по автору
void sort_by_author(Item *sources, const int quantity)
{
    for (int i = 0; i < quantity; ++i)
    {
        for (int j = 0; j < quantity - 1 - i; ++j)
        {
            if (sources[j].author > sources[j + 1].author)
            {
                swap(sources[j], sources[j + 1]);
            }
        }
    }
}

//Сортировка массива по издательству
void sort_by_publisher(Item *sources, const int quantity)
{
    for (int i = 0; i < quantity; ++i)
    {
        for (int j = 0; j < quantity - 1 - i; ++j)
        {
            if (sources[j].publisher > sources[j + 1].publisher)
            {
                swap(sources[j], sources[j + 1]);
            }
        }
    }
}

//Сортировка массива по типу
void sort_by_source_type(Item *sources, const int quantity)
{
    for (int i = 0; i < quantity; ++i)
    {
        for (int j = 0; j < quantity - 1 - i; ++j)
        {
            if (sources[j].source_type > sources[j + 1].source_type)
            {
                swap(sources[j], sources[j + 1]);
            }
        }
    }
}

//Сортировка массива по году
void sort_by_year(Item *sources, const int quantity)
{
    for (int i = 0; i < quantity; ++i)
    {
        for (int j = 0; j < quantity - 1 - i; ++j)
        {
            if (sources[j].year > sources[j + 1].year)
            {
                swap(sources[j], sources[j + 1]);
            }
        }
    }
}

//Сортировка массива по жанру
void sort_by_genre(Item *sources, const int quantity)
{
    for (int i = 0; i < quantity; ++i)
    {
        for (int j = 0; j < quantity - 1 - i; ++j)
        {
            if (sources[j].genre > sources[j + 1].genre)
            {
                swap(sources[j], sources[j + 1]);
            }
        }
    }
}

//меню сортування книг
void sort_sources(Item *sources, const int quantity)
{
    enum Sorting
    {
        exit, source_type, name, author, year, genre, publisher
    };
    int choice;
    do
    {
        do
        {
            cout << "Sort sources by :" << endl
                << source_type << ". Type of source" << endl
                << name << ". Name" << endl
                << author << ". Author" << endl
                << year << ". Year" << endl
                << genre << ". Genre" << endl
                << publisher << ". Publisher" << endl
                << exit << ". Exit" << endl << endl
                << "Enter the parameter : ";
            cin >> choice;
        } while (choice < exit || choice > publisher);
        switch (choice)
        {
        case source_type: sort_by_source_type(sources, quantity);
            break;
        case name: sort_by_name(sources, quantity);
            break;
        case author: sort_by_author(sources, quantity);
            break;
        case year: sort_by_year(sources, quantity);
            break;
        case genre: sort_by_genre(sources, quantity);
            break;
        case publisher: sort_by_publisher(sources, quantity);
            break;
        case 0: cout << "Thanks!" << endl;
            break;
        default:
            break;
        }
        system("cls");
        cout << "Sorted ";
        print_sources(sources, quantity);
    } while (choice != 0);
}
#pragma endregion

#pragma region Find_source
//Поиск книг по автору
void search_by_author(Item *sources, const int quantity) // Можна шукати як по прізвищу так і по імені
{
    int counter = 0;
    cin.ignore();
    string search_word;
    cout << "Enter author's name : ";
    getline(cin, search_word);
    bool is_in = false;
    for (int i = 0; i < quantity; ++i)
    {
        int k = -1;
        k = sources[i].author.find(search_word);
        if (k >= 0)
        {
            is_in = true;
            cout << "--------------------------------------------------------------------------------" << endl;
            print_source(sources + i);
            ++counter;
        }
    }
    if (is_in == false)
    {
        cout << "No match found." << endl;
    }
    else
    {
        cout << endl << counter << "sources found" << endl << endl << endl;
    }
}

//Поиск книги по названию
void search_by_name(Item *sources, const int quantity) // Можна шукати по будь-якому слові в назві
{
    int counter = 0;
    cin.ignore();
    string search_word;
    cout << "Enter the name of book: ";
    getline(cin, search_word);
    bool is_in = false;
    for (int i = 0; i < quantity; ++i)
    {
        int k = -1;
        k = sources[i].name.find(search_word);
        if (k >= 0)
        {
            is_in = true;
            cout << "--------------------------------------------------------------------------------" << endl;
            print_source(sources + i);
            ++counter;
        }
    }
    if (is_in == false)
    {
        cout << "--------------------------------------------------------------------------------" << endl
            << "No match found." << endl << endl
            << "--------------------------------------------------------------------------------" << endl;
    }
    else
    {
        cout << endl << counter << "sources found" << endl << endl << endl;
    }
}

void search_by_publisher(Item *sources, const int quantity) // Можна шукати по будь-якому слові в назві
{
    int counter = 0;
    cin.ignore();
    string search_word;
    cout << "Enter the publisher of sources : ";
    getline(cin, search_word);
    bool is_in = false;
    for (int i = 0; i < quantity; ++i)
    {
        int k = -1;
        k = sources[i].publisher.find(search_word);
        if (k >= 0)
        {
            is_in = true;
            cout << "--------------------------------------------------------------------------------" << endl;
            print_source(sources + i);
            ++counter;
        }
    }
    if (is_in == false)
    {
        cout << "--------------------------------------------------------------------------------" << endl
            << "No match found." << endl << endl
            << "--------------------------------------------------------------------------------" << endl;
    }
    else
    {
        cout << endl << counter << "sources found" << endl << endl << endl;
    }
}

void search_book(Item *sources, const int quantity)
{
    int choice;
    do
    {
        do
        {
            cout << "Search book by :" << endl
                << "1. Name" << endl
                << "2. Author" << endl
                << "3. Publisher" << endl
                << "0. Exit" << endl << endl
                << "Enter the parameter : ";
            cin >> choice;
        } while (choice < 0 || choice > 3);

        switch (choice)
        {
        case 1: search_by_name(sources, quantity);
            break;
        case 2: search_by_author(sources, quantity);
            break;
        case 3: search_by_publisher(sources, quantity);
            break;
        case 0: cout << "Thanks!" << endl;
            break;
        default:
            break;
        }
    } while (choice != 0);
}

void search_magazine(Item *sources, const int quantity)
{
    string name;
    cout << "Enter the name of magazine or news paper : ";
    cin.ignore();
    getline(cin, name);
    int year;
    cout << "Enter the year of magazine or news paper : ";
    cin >> year;
    Item *search_source = new Item;
    bool is_in = false;
    for (Item *ptr = sources; ptr < sources + quantity; ++ptr)
    {
        int k = -1;
        k = ptr->name.find(name);
        if (k >= 0)
        {
            if (ptr->year == year)
            {
                is_in = true;
                cout << "--------------------------------------------------------------------------------" << endl;
                print_source(ptr);
                break;
            }
        }
    }
    if (is_in == false)
    {
        cout << "--------------------------------------------------------------------------------" << endl
        << "No match found." << endl << endl
        << "--------------------------------------------------------------------------------" << endl;
    }
}

void search_source(Item *sources, const int quantity)
{
    enum Variants
    {
        exit, book, magazine
    };
    int choice = 0;
    do
    {
        do
        {
            cout << "Choose what do you want to find :" << endl
                << book << ". Book" << endl
                << magazine << ". Magazine or News paper" << endl
                << exit << ". Cancel" << endl
                << "Your choice : ";
            cin >> choice;
        } while (choice < exit || choice > magazine);
        switch (choice)
        {
        case book: search_book(sources, quantity);
            break;
        case magazine: search_magazine(sources, quantity);
            break;
        case exit: cout << "CANCELED" << endl;
            break;;
        default:
            break;
        }
    } while (choice != exit);
}
#pragma endregion

/*void create_array(ifstream *read_file, int lib_size, Item *sources)
{
    string item_param;
    int i = 0;
    while (!read_file.eof())
    {
    cout << i << endl;
    getline(read_file, item_param, ';');
    sources[i].source_type = item_param;

    getline(read_file, item_param, ';');
    sources[i].name = item_param;
    cout << sources[i].name << endl;

    getline(read_file, item_param, ';');
    sources[i].author = item_param;

    getline(read_file, item_param, ';');
    sources[i].year = atoi(item_param.c_str()); //i = atoi(string_name.c_str());

    getline(read_file, item_param, ';');
    sources[i].genre = item_param;

    getline(read_file, item_param, ';');
    sources[i].publisher = item_param;

    getline(read_file, item_param, ';');
    sources[i].is_given = item_param;

    i++;
    read_file.seekg(2, ios::cur);
    }
}*/

int get_sources_quantity(ifstream read_file)
{
    int quant = 0;
    string number;
    read_file >> number;
    quant = atoi(number.c_str());
    return quant;
}

int get_position(int lib_size)
{
    int counter = 0;
    if (lib_size <= 0)
    {
        counter = 0;
    }
    else if (lib_size < 10)
    {
        counter = 1;
    }
    else
    {
        do
        {
            lib_size /= 10;
            ++counter;
        } while (lib_size >= 1);
    }
    return counter;
}

void main()
{

    ifstream read_file;
    string read_file_name = "Library.txt";

    read_file.open(read_file_name, ios_base::in);
    if (!read_file.is_open())
    {
        cerr << "Cannot open " << read_file_name << " for reading. Exiting...." << endl;
        system("pause");
        exit(1);
    }

    int lib_size = 0;
    string number;
    read_file >> number;
    lib_size = atoi(number.c_str());
    cout << "Library consists of " << lib_size << " sources" << endl << endl;
    Item *sources = new Item[lib_size];
    string item_param;
    int i = 0;
    int position = get_position(lib_size);
    read_file.seekg(position + 2);

    for (; i < lib_size; ++i)
    {
        getline(read_file, item_param, ';');
        sources[i].serial_number = atoi(item_param.c_str());

        getline(read_file, item_param, ';');
        sources[i].source_type = item_param;

        getline(read_file, item_param, ';');
        sources[i].name = item_param;

        getline(read_file, item_param, ';');
        sources[i].author = item_param;

        getline(read_file, item_param, ';');
        sources[i].year = atoi(item_param.c_str()); //i = atoi(string_name.c_str());

        getline(read_file, item_param, ';');
        sources[i].genre = item_param;

        getline(read_file, item_param, ';');
        sources[i].publisher = item_param;

        getline(read_file, item_param, ';');
        sources[i].is_given = item_param;

        read_file.seekg(2, ios::cur);
    }

    int choice;
    enum menu
    {
        Exit,
        Add,
        Print,
        Edit,
        Sort,
        Search
    };

    do
    {
        do
        {
            cout << Add << ". Add source" << endl
                << Print << ". Print sources" << endl
                << Edit << ". Edit sources" << endl
                << Sort << ". Sort sources" << endl
                << Search << ". Search source" << endl
                << Exit << ". Exit" << endl << endl
                << "Enter the action : ";
            cin >> choice;
        } while (choice < 0 || choice > 5);
        switch (choice)
        {
        case menu::Add: add_source(sources, lib_size);
            break;
        case menu::Print:
            print_sources(sources, lib_size);
            break;
        case menu::Edit:
            edit_book(sources, lib_size);
            break;
        case menu::Sort:
            sort_sources(sources, lib_size);
            break;
        case menu::Search:
            search_source(sources, lib_size);
            break;
        case menu::Exit:
            cout << "Good bye!" << endl;
        default:
            break;
        }
    } while (choice != 0);

    delete[] sources;
    system("pause");
}

57

(14 відповідей, залишених у C++)

чому  не можна прикріпити два файли до повідомлення?

58

(14 відповідей, залишених у C++)

Ось два файли: файл коду і файл з бібліотекою. Думаю, так буде легше розібратися

59

(14 відповідей, залишених у C++)

За file_size дякую. поправив.
Ви маєте на увазі замінити *dst_ptr = *src_ptr на
dst_ptr->serial_number = src_ptr->serial_number
dst_ptr->source_type = src_ptr->source_type
..... і так далі?
Але у мене ніби з цим проблем не було і елементи копіювались як має бути. Я перевіряв. Коротше, я замінив, але нічого від того не змінилося. Може мені, коли я створюю масив з додатковою структурою, проініціалізувати елементи останньої нулями?

60

(14 відповідей, залишених у C++)

можу кинути МЕЙН, але там буде ще менш зрозуміло, бо я копіюю інформацію з файлу (книги бібліотеки) в масив структур, тому доведеться прикріпити і файл.
оскільки вся програма написана з string-ами, то в масив чарів перероблювати не буду.
Не розумію, що означає "перевизначте власний operator =(Item&, Item&)"... можна на прикладі або детальніше?

ПС. Додав коментарі в код першого посту

int get_sources_quantity(ifstream read_file)
{
    int quant = 0;
    string number;
    read_file >> number;
    quant = atoi(number.c_str());
    return quant;
}

int get_position(int lib_size)
{
    int counter = 0;
    if (lib_size <= 0)
    {
        counter = 0;
    }
    else if (lib_size < 10)
    {
        counter = 1;
    }
    else
    {
        do
        {
            lib_size /= 10;
            ++counter;
        } while (lib_size >= 1);
    }
    return counter;
}

void main()
{

    ifstream read_file;
    string read_file_name = "Library.txt";

    read_file.open(read_file_name, ios_base::in);
    if (!read_file.is_open())
    {
        cerr << "Cannot open " << read_file_name << " for reading. Exiting...." << endl;
        system("pause");
        exit(1);
    }

    int lib_size = 0;
    string number;
    read_file >> number;
    lib_size = atoi(number.c_str());
    cout << "Library consists of " << lib_size << " sources" << endl << endl;
    Item *sources = new Item[lib_size];
    string item_param;
    int i = 0;
    int position = get_position(lib_size);
    read_file.seekg(position + 2);

    for (; i < lib_size; ++i)
    {
        getline(read_file, item_param, ';');
        sources[i].serial_number = atoi(item_param.c_str());

        getline(read_file, item_param, ';');
        sources[i].source_type = item_param;

        getline(read_file, item_param, ';');
        sources[i].name = item_param;

        getline(read_file, item_param, ';');
        sources[i].author = item_param;

        getline(read_file, item_param, ';');
        sources[i].year = atoi(item_param.c_str()); //i = atoi(string_name.c_str());

        getline(read_file, item_param, ';');
        sources[i].genre = item_param;

        getline(read_file, item_param, ';');
        sources[i].publisher = item_param;

        getline(read_file, item_param, ';');
        sources[i].is_given = item_param;

        read_file.seekg(2, ios::cur);
    }

    int choice;
    enum menu
    {
        Exit,
        Add,
        Print,
        Edit,
        Sort,
        Search
    };

    do
    {
        do
        {
            cout << Add << ". Add source" << endl
                << Print << ". Print sources" << endl
                << Edit << ". Edit sources\n" <<
                Sort << ". Sort sources\n" <<
                Search << ". Search book\n" <<
                Exit << ". Exit" << endl;
            cout << "Enter the action : ";
            cin >> choice;
        } while (choice < 0 || choice > 5);
        switch (choice)
        {
        case menu::Add: add_source(sources, lib_size);
            break;
        case menu::Print:
            print_sources(sources, lib_size);
            break;
        case menu::Edit:
            edit_book(sources, lib_size);
            break;
        case menu::Sort:
            sort_sources(sources, lib_size);
            break;
        case menu::Search:
            search_book(sources, lib_size);
            break;
        case menu::Exit:
            cout << "Good bye!" << endl;
        default:
            break;
        }
    } while (choice != 0);

    delete[] sources;
    system("pause");
}