Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Курсовая Голиков Илья.docx
Скачиваний:
17
Добавлен:
19.01.2023
Размер:
4.11 Mб
Скачать

Заключение

В ходе выполнения работы была достигнута основная цель – автоматизация учёта продаж авиабилетов, для чего средствами языка программирования C++ была разработана программа. После общей постановки задачи разработаны алгоритмы работы всех модулей программы, используемая структура данных.

После этого с в среде программирования Microsoft Visual Studio реализовано два варианта программы – с консольным и с графическим интерфейсом. Проведено тестирование разработанного приложения, выявлены и исправлены ошибки в работе, добавлен недостающий функционал.

В первом разделе курсовой работы была проанализирована текущая ситуация и задана основная цель работы.

Во втором разделе она была уточнена и расширена дополнительными задачами, описан требуемый функционал.

В третьем были описаны основные используемые в программе функции, переменные и структуры данных.

В четвёртом разделе в виде блок-схем представлена программная реализация используемых алгоритмов.

В пятом разделе продемонстрирована работа всех функций созданных приложений.

В заключение можно сказать, что успешно достигнута основная цель курсовой работы, полностью выполнены все задачи, созданный программный продукт готов к реальному использованию.

Список использованных источников

  1. Шилдт, Г. Полный справочник по C++ 4-е издание[Текст]/ Шилдт, Г. – СПб, 2006.

  2. Райт, В. Азбука обоев[Текст]/ Райт, В.-М.,2012.

  3. Шилдт, Г. С++ Базовый курс[Текст]/ Шилдт, Г. – СПб, 2008.

  4. Документация по Microsoft C++, C и Ассемблеру - [Электронный ресурс] URL: https://docs.microsoft.com/ru-RU/cpp/?view=msvc-170, свободный. – Загл. С экрана. – Яз. Рус. (дата обращения 02.06.2022).

  5. Функция strtok – [Электронный ресурс] URL: http://cppstudio.com/post/747/, свободный. – Загл. С экрана. – Яз. Рус. (дата обращения 28.05.2022).

  6. Лафоре, Р. Объектно-ориентированное программирование в C++ 4-е издание[Текст]/ Лафоре, Р.,2004.

  7. Кеннинг, Э. Эффективное программирование на C++. Практическое программирование на примерах[Текст]/ Кеннинг, Э., 2019.

  8. Дейтел, Х. Как программировать на C++ 5-е издание[Текст]/ Дейтел, Х.-2006.

  9. Шилдт, Г. C++ для начинающих. Шаг за шагом[Текст]/ Шилдт, Г. – СПб, 2013.

  10. Рэнди, С. C++ для чайников[Текст]/ Рэнди, С., 2015.

  11. Саттер, Г. Решение сложных задач на С++[Текст]/ Саттер, Г. 2002.

  12. Страуструп, Б. Язык программирования С++[Текст]/ Страуструп, Б. -1986.

Приложение Приложение а – Исходный код консольного приложения

А1 – Содержимое заголовочного файла “Headers.h”

#pragma once

#include <string>

#include <iostream>

#include <iomanip>

#include <fstream>

using namespace std;

struct ticket {

int id;

string surname;

string name;

string patr;

int day;

int month;

int year;

string from;

string to;

string luggage;

string company;

string fl_number;

int price;

int date_simp;

};

int db_out();

int search(bool id_option);

int adding();

int deleting();

void read_data(ticket * tickets, int count_of);

int count_of_lines();

//Sorting functions for db_out()

//Sort array by surname

void bubble_sort_surn(ticket* words, int length);

//Sort array by surname

void bubble_sort_comp(ticket* words, int length);

//Sort array by date

void qsort_date(ticket* tickets, int length);

//Sort array by price

void qsort_price(ticket* tickets, int length);

//Comparse two words

bool word_comparsion(string left, string right);

char MyToLower(char r);

void separator_output(int length, char line_type);

void engine(ticket* tickets, int length, char choice, bool id_option);

void print(ticket* tickets, int i, bool id_option, int counter);

void header_print();

int id_function();

А2 – Исходный код функции main()

#include "Headers.h"

using namespace std;

int main()

{

system("chcp 1251");

system("mode con cols=180");

system("color f0");

bool execution = true;

char choice;

while (execution) {

string words[5] = {"Вывод БД", "Поиск по БД", "Добавление элементов", "Удаление элементов", "Выход из программы"};

system("cls");

//Print menu

separator_output(43, '=');

cout << " | Код | Вариант |\n";

separator_output(43, '=');

for (short i = 1; i < 6; i++)

{

cout << " | " << i << " | " << setw(31) << left << words[i - 1] << "|\n";

separator_output(43, '-');

}

cout << endl << " Выберите вариант: ";

cin >> choice;

//If choice is not an int, try again

if (isalpha(choice))

{

cout << endl << " Не похоже на число!\n\n ";

system("pause");

system("cls");

continue;

}

switch (choice)

{

case '1':

db_out();

system("cls");

break;

case '2':

search(false);

system("cls");

break;

case '3':

adding();

system("cls");

break;

case '4':

deleting();

system("cls");

break;

case '5':

execution = false;

break;

default:

cout << "\n Введённое число не похоже на вариант! \n";

system("pause");

system("cls");

break;

}

}

return 0;

}

А3 – Исходный код функции db_out()

#include "Headers.h"

int db_out() {

system("cls");

int count_of = count_of_lines();

int choice = 0;

ticket* tickets = new ticket[count_of];

read_data(tickets, count_of);

cout << " По какому параметру отсортировать?\n";

cout << " 1 - Фамилия 2 - Дата 3 - Цена 4 - Авиакомпания 0 - Не сортировать\n > ";

cin >> choice;

switch (choice)

{

case 1:

bubble_sort_surn(tickets, count_of);

break;

case 2:

qsort_date(tickets, count_of);

break;

case 3:

qsort_price(tickets, count_of);

break;

case 4:

bubble_sort_comp(tickets, count_of);

break;

default:

break;

}

//Print header

header_print();

//Print the database

for (int i = 0; i < count_of; i++)

{

print(tickets, i, false, i + 1);

}

//Free up memory and close database file

delete[] tickets;

cout << endl << endl;

system("pause");

return 0;

}

А4 – Исходный код функции search()

#include "Headers.h"

int search(bool id_option) {

system("cls");

bool next = true;

string line; // For temp lines

int count_of = count_of_lines(), i = 0;

char choice = 0;

//Create the array of passenger structures

ticket* tickets = new ticket[count_of];

//Close file and open it from the beginning

read_data(tickets, count_of);

while (next) {

cout << " Введите категорию поиска\n";

cout << " 1 - Фамилия 2 - Год и месяц 3 - Город 4 - Авиакомпания\n > ";

cin >> choice;

switch (choice)

{

case '1':

engine(tickets, count_of, choice, id_option);

next = false;

break;

case '2':

engine(tickets, count_of, choice, id_option);

next = false;

break;

case '3':

engine(tickets, count_of, choice, id_option);

next = false;

break;

case '4':

engine(tickets, count_of, choice, id_option);

next = false;

break;

default:

cout << "\n Неверный вариант!";

break;

}

}

return 0;

}

А5 – Исходный код функции adding() и функции id_function()

#include "Headers.h"

using namespace std;

int adding() {

bool next = true;

string surn, name, patr, day, month, year, comp, fl_num, from, to, lugg, price;

char date[15], * token = 0, * word, sep[] = " ./", corr;

int id;

system("cls");

//Opening database file

ofstream data;

data.open("data.txt", ios_base::app);

cout << "\n Примечание: дата вводится в формате дд.мм.гггг\n";

while (next)

{

//Reading of ticket data

cout << "\n Введите данные билета. \"0 - выход\"";

getchar();

cout << "\n\n Фамилия > ";

getline(cin, surn);

if (surn == "0\0") {

next = false;

continue;

}

cout << " Имя > ";

getline(cin, name);

cout << " Отчество > ";

getline(cin, patr);

cout << " Дата вылета > ";

fgets(date, 15, stdin);

//getchar();

//getchar();

cout << " Откуда > ";

getline(cin, from);

cout << " Куда > ";

getline(cin, to);

cout << " Багаж > ";

getline(cin, lugg);

cout << " Компания > ";

getline(cin, comp);

cout << " Номер рейса > ";

getline(cin, fl_num);

cout << " Стоимость билета > ";

getline(cin, price);

//Remove \n from date

for (char& i : date) if (i == '\n') i = '\0';

//Convert the first three parts of the number to the day, month and number;

word = strtok_s(date, sep, &token);

day = word;

word = strtok_s(NULL, sep, &token);

month = word;

word = strtok_s(NULL, sep, &token);

year = word;

if (stoi(year) - 2000 < 0) {

cout << "\n Формат ввода даты неправильный. Попробуйте ещё раз!\n";

continue;

}

//Is data correct?

cout << "\n\n Данные корректны? (д/н) ";

cin >> corr;

//If it is incorrect to do the next iteration.

//If not, continue the current one

if (!(corr == 'д' || corr == 'Д')) continue;

else cout << " Добавлено\n";

id = id_function();

//Write new data with separator to the end of database file

data << "####" << endl << id << endl << surn << endl << name << endl << patr << endl;

data << day << endl << month << endl << year << endl;

//Write other data to the database

data << from << endl << to << endl << lugg << endl << comp << endl << fl_num << endl << price << endl;

}

//Close the file in the end of program

data.close();

return 0;

}

int id_function() {

int id;

//Create id_reader object

ifstream id_reader ("id.txt");

//If not id.txt create it and add '1' there

if (id_reader.bad()) {

ofstream id_creator("id.txt");

id_creator << 1 << endl;

id_creator.close();

}

//If id.txt exists read id, concatenate it and write again

else {

id_reader.open("data.txt");

id_reader >> id;

id_reader.close();

}

ofstream id_writer;

id_writer.open("id.txt");

id_writer << ++id;

id_writer.close();

return id;

}

А6 - Исходный код функции deleting()

#include "Headers.h"

using namespace std;

int deleting() {

system("cls");

char ids[50], *word, * token = 0, sep[] = " .,:\n", choice;

int count = 0, curr_id, count_of = count_of_lines();

ticket* tickets = new ticket[count_of];

read_data(tickets, count_of);

search(true);

getchar();

cout << "\n\n Введите несколько id элементов для удаления\n > ";

fgets(ids, 50, stdin);

//Print header of the table of deleted items

header_print();

//Print lines for deletion

word = strtok_s(ids, sep, &token);

while (word) {

curr_id = atoi(word);

for (int i = 0; i < count_of; i++) {

if (tickets[i].id == curr_id) {

tickets[i].id = 0;

print(tickets, i, true, i + 1);

}

}

word = strtok_s(NULL, sep, &token);

}

cout << "\n\n Удалить указанные элементы? (д/н) > ";

cin >> choice;

if (!(choice == 'Д' || choice == 'д')) {

cout << " Удаление отменено!";

}

else

{

ofstream data;

data.open("data.txt");

for (int i = 0; i < count_of; i++)

{

if (tickets[i].id == 0) continue;

data << "####" << endl

<< tickets[i].id << endl

<< tickets[i].surname << endl

<< tickets[i].name << endl

<< tickets[i].patr << endl

<< tickets[i].day << endl

<< tickets[i].month << endl

<< tickets[i].year << endl

<< tickets[i].from << endl

<< tickets[i].to << endl

<< tickets[i].luggage << endl

<< tickets[i].company << endl

<< tickets[i].fl_number << endl

<< tickets[i].price << endl;

}

data.close();

}

delete[] tickets;

cout << endl << endl << " ";

system("pause");

return 0;

}

А7 – Исходный код фукнции count_of_lines()

#include "Headers.h"

int count_of_lines() {

string line; // For temp lines

int count_of = 0;

//Open the database in read mode

ifstream data;

data.open("data.txt");

//Count the number of elements

while (!data.eof()) {

getline(data, line);

if (line == "####") count_of++;

}

data.close();

return count_of;

}

Б1.8 – Исходный код функции read_data()

#include "Headers.h"

/// <summary>

/// The function reads data from a file data.txt and passes them to the tickets array

/// </summary>

/// <param name="tickets"> - array for storing read data</param>

/// <param name="count_of"> - length of tickets array</param>

void read_data(ticket * tickets, int count_of) {

string line; // For temp lines

int i = 0;

ifstream data;

data.open("data.txt");

//Read info about tickets and add it to array

while (i < count_of && ! data.eof()){

getline(data, line);

//Устранение ошибок чтения и позиции в файле. В крайнем случае пропускается строка, но не возникает проблем

while (line != "####") {

getline(data, line);

};

//Read the ID and convert it to int

getline(data, line);

tickets[i].id = stoi(line);

//Read data

getline(data, tickets[i].surname);

getline(data, tickets[i].name);

getline(data, tickets[i].patr);

//Read date and convert it to int

getline(data, line);

tickets[i].day = stoi(line);

getline(data, line);

tickets[i].month = stoi(line);

getline(data, line);

tickets[i].year = stoi(line);

//Read onother data

getline(data, tickets[i].from);

getline(data, tickets[i].to);

getline(data, tickets[i].luggage);

getline(data, tickets[i].company);

getline(data, tickets[i].fl_number);

getline(data, line);

tickets[i].price = stoi(line);

tickets[i].date_simp = fabs(tickets[i].year - 2000) * 365 + tickets[i].month * 30 + tickets[i].day;

i++;

}

data.close();

}

А8 – Исходный код функции engine()

#include "Headers.h"

void engine(ticket* tickets, int length, char choice, bool id_option) {

short counter = 0, month, year;

string skey, temp;

switch (choice)

{

case '1':

getchar();

cout << "\n Введите ключ поиска: ";

cin >> skey;

header_print();

for (char& i : skey) i = MyToLower(i);

for (int i = 0; i < length; i++)

{

temp = tickets[i].surname;

for (char& i : temp) i = MyToLower(i);

if (temp.find(skey) != string::npos) {

print(tickets, i, id_option, ++counter);

}

}

if (!id_option) {

cout << endl << endl;

system("pause");

}

break;

case '2':

cout << "\n Год > ";

cin >> year;

cout << " Месяц > ";

cin >> month;

header_print();

for (int i = 0; i < length; i++) {

if (tickets[i].month == month && tickets[i].year == year) print(tickets, i, id_option, ++counter);

}

if (!id_option) {

cout << endl << endl;

system("pause");

}

break;

case '3':

getchar();

cout << "\n Введите ключ поиска: ";

cin >> skey;

header_print();

for (char& i : skey) i = MyToLower(i);

for (int i = 0; i < length; i++)

{

temp = tickets[i].from;

for (char& i : temp) i = MyToLower(i);

if (temp.find(skey) != string::npos) {

print(tickets, i, id_option, ++counter);

}

temp = tickets[i].to;

for (char& i : temp) i = MyToLower(i);

if (temp.find(skey) != string::npos) {

print(tickets, i, id_option, ++counter);

}

}

if (!id_option) {

cout << endl << endl;

system("pause");

}

break;

case '4':

getchar();

cout << "\n Введите ключ поиска: ";

cin >> skey;

header_print();

for (char& i : skey) i = MyToLower(i);

for (int i = 0; i < length; i++)

{

temp = tickets[i].company;

for (char& i : temp) i = MyToLower(i);

if (temp.find(skey) != string::npos) {

print(tickets, i, id_option, ++counter);

}

}

if (!id_option) {

cout << endl << endl;

system("pause");

}

break;

}

}

А9 – Исходный код функции header_print()

#include "Headers.h"

void header_print() {

short width = 174;

//Print the header of database

cout << "\n Билеты\n";

separator_output(width, '=');

cout << " | " << setw(6) << left << "№" << " | "

<< setw(16) << left << "Фамилия" << " | "

<< setw(12) << left << "Имя" << " | "

<< setw(15) << left << "Отчество" << " | "

<< setw(12) << left << "Дата вылета" << " | "

<< setw(20) << left << "Откуда" << " | "

<< setw(20) << left << "Куда" << " | "

<< setw(4) << left << "Багаж" << " | "

<< setw(10) << left << "Перевозчик" << " | "

<< setw(7) << left << "№ рейса" << " | "

<< setw(6) << left << "Цена" << " |" << endl;

separator_output(width, '=');

}

А10 – Исходный код фукнции MyToLower()

#include <iostream>

using namespace std;

char MyToLower(char r)

{

switch (r)

{

case 'А': r = 'а'; break;

case 'Б': r = 'б'; break;

case 'В': r = 'в'; break;

case 'Г': r = 'г'; break;

case 'Д': r = 'д'; break;

case 'Е': r = 'е'; break;

case 'Ж': r = 'ж'; break;

case 'З': r = 'з'; break;

case 'И': r = 'и'; break;

case 'Й': r = 'й'; break;

case 'К': r = 'к'; break;

case 'Л': r = 'л'; break;

case 'М': r = 'м'; break;

case 'Н': r = 'н'; break;

case 'О': r = 'о'; break;

case 'П': r = 'п'; break;

case 'Р': r = 'р'; break;

case 'С': r = 'с'; break;

case 'Т': r = 'т'; break;

case 'У': r = 'у'; break;

case 'Ф': r = 'ф'; break;

case 'Х': r = 'х'; break;

case 'Ц': r = 'ц'; break;

case 'Ч': r = 'ч'; break;

case 'Ш': r = 'ш'; break;

case 'Щ': r = 'щ'; break;

case 'Ъ': r = 'ъ'; break;

case 'Ы': r = 'ы'; break;

case 'Ь': r = 'ь'; break;

case 'Э': r = 'э'; break;

case 'Ю': r = 'ю'; break;

case 'Я': r = 'я'; break;

case 'A': r = 'a'; break;

case 'B': r = 'b'; break;

case 'C': r = 'c'; break;

case 'D': r = 'd'; break;

case 'E': r = 'e'; break;

case 'F': r = 'f'; break;

case 'G': r = 'g'; break;

case 'H': r = 'h'; break;

case 'I': r = 'i'; break;

case 'J': r = 'j'; break;

case 'K': r = 'k'; break;

case 'L': r = 'l'; break;

case 'M': r = 'm'; break;

case 'N': r = 'n'; break;

case 'O': r = 'o'; break;

case 'P': r = 'p'; break;

case 'Q': r = 'q'; break;

case 'R': r = 'r'; break;

case 'S': r = 's'; break;

case 'T': r = 't'; break;

case 'U': r = 'u'; break;

case 'V': r = 'v'; break;

case 'W': r = 'w'; break;

case 'X': r = 'x'; break;

case 'Y': r = 'y'; break;

case 'Z': r = 'z'; break;

}

return (r);

}

А11– Исходный код функции print()

#include "Headers.h"

void print(ticket* tickets, int i, bool id_option, int counter) {

short width = 174;

//If id_option is true program print id of ticket in the first column

//Else print number of line

cout << " | ";

if (id_option) cout << setw(6) << left << tickets[i].id;

else cout << setw(6) << left << counter;

cout << " | " << setw(16) << left << tickets[i].surname

<< " | " << setw(12) << left << tickets[i].name

<< " | " << setw(15) << left << tickets[i].patr

<< " | " << setw(2) << left << tickets[i].day

<< "." << setw(2) << left << tickets[i].month

<< "." << setw(6) << left << tickets[i].year

<< " | " << setw(21) << left << tickets[i].from

<< " | " << setw(20) << left << tickets[i].to

<< " | " << setw(4) << left << tickets[i].luggage

<< " | " << setw(10) << left << tickets[i].company

<< " | " << setw(7) << left << tickets[i].fl_number

<< " | " << setw(6) << left << tickets[i].price

<< " |" << endl;

separator_output(width, '-');

}

А12 – Исходный код функции separator_output()

#include <iostream>

using namespace std;

void separator_output(int length, char line_type) {

cout << " ";

for (int i = 0; i < length; i++) cout << line_type;

cout << endl;

}

А13 – Исходный код функции word_comparsion()

#include "Headers.h"

bool word_comparsion(string left, string right) {

short i = 0;

for (i; i < 4; i++)

{

if (left[i] < right[i]) return true;

if (left[i] > right[i]) return false;

}

return true;

}