
Лабораторная работа №3 Вариант 2
.2.rtfФЕДЕРАЛЬНОЕ АГЕНТСТВО ПО ОБРАЗОВАНИЮ
ГОСУДАРСТВЕННОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ
ВЫСШЕГО ПРОФЕССИОНАЛЬНОГО ОБРАЗОВАНИЯ
ЛИПЕЦКИЙ ГОСУДАРСТВЕННЫЙ ТЕХНИЧЕСКИЙ УНИВЕРСИТЕТ
КАФЕДРА АВТОМАТИЗИРОВАННЫХ СИСТЕМ УПРАВЛЕНИЯ
Лабораторная работа №3
по дисциплине
«Программирование на ЯВУ»
на тему:
«Обработка базовых списковых структур данных
(Последовательность, стек, очередь, дек, список)»
|
Студент |
|
|
|
Дырдин Н.В. |
|
||||||||||
|
|
|
подпись, дата |
|
фамилия, инициалы |
|
||||||||||
|
Группа |
|
АС - 09 |
|
|
|
||||||||||
|
|
|
|
|
|
|
||||||||||
|
Принял |
|
|
|
Фарафонов А.С. |
|
||||||||||
|
|
|
|
|
|
|
||||||||||
|
ученая степень, звание |
|
подпись, дата |
|
фамилия, инициалы |
|
Липецк 2010
-
Задание
Написать программу, реализующую ввод данных из текстового, двоичного файлов и с клавиатуры и вывод данных в текстовый, двоичный файл и на экран. Для хранения данных использовать заданную списковую структуру данных.
Данные представляют собой структуру из 2-х элементов. Ввод-вывод в двоичный файл осуществлять чтением-записью области памяти, занимаемой структурой. Порядок ввода-вывода определяется спецификой списковой структуры.
Количество элементов не должно быть ограничено (обязательно использовать динамическое выделение памяти).
Программа должна быть реализована в виде меню, имеющего, приблизительно, следующую структуру:
-
Ввод
-
Из текстового файла
-
Из двоичного файла
-
С клавиатуры
-
-
Очистить
-
Вывод
-
В текстовый файл
-
В двоичный файл
-
На экран
-
-
Выход
22 |
Фамилия студента, рейтинг |
22 |
Стек |
|
-
Блок-схема
-
Листинг программы
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
struct list{
list *head;
list *tail;
list *next;
int raiting;
char name[64];
list() {head = tail = next = NULL;};
virtual void add(int raiting, char f[64], int len) = 0;
virtual void output(int check = 0) = 0;
inline void erase(char *str);
};
inline void list::erase(char *str)
{
if(!head){
cout << str << " is clear!" << endl;
}
else{
list *l;
l = head;
head = head->next;
delete l;
erase(str);
}
}
struct stack : public list{
public:
void add(int rating, char f[64], int len);
void output(int check = 0);
};
void stack::add(int raiting, char f[64], int len)
{
list *item;
item = new stack;
if(!item){
cout << "Memory error!" << endl;
exit(1);
}
item->raiting = raiting;
for(int i = 0; i < len; i++){
item->name[i] = f[i];
}
item->name[len] = '\0';
if(head){
item->next = head;
}
head = item;
if(!tail){
tail = head;
}
}
void stack::output(int check)
{
if(head){
int tmp;
char *tmp2;
tmp = head->raiting;
tmp2 = head->name;
head = head->next;
if(check == 0) cout << "Student: " << tmp2 << ", rating = " << tmp << endl, output();
}
}
void in_action(stack &s, char action[10]);
inline void binary_write(stack &s);
inline void binary_read(stack &s);
inline void text_write(stack &s);
inline void text_read(stack &s);
void help();
int main()
{
system ("color 74");
stack s;
while(true){
char action[10];
cout << "Input action = ";
cin >> action;
in_action(s, action);
}
}
void in_action(stack &s, char action[10])
{
if(strstr("add", action)){
int raiting;
char name[64];
cout << "What name of student? = ";
cin >> name;
cout << "What raiting of student? = ";
cin >> raiting;
s.add(raiting, name, strlen(name));
}
else if(strstr("show", action)){
stack s2 = s;
s2.output();
}
else if(strstr("retr", action)){
s.output(1);
}
else if(strstr("clear", action)){
s.erase("Stack");
}
else if(strstr("wB", action)){
stack s2 = s;
system("erase binary.stack /Q");
binary_write(s2);
}
else if(strstr("rB", action)){
binary_read(s);
}
else if(strstr("close", action)){
exit(1);
}
else if(strstr("wT", action)){
stack s2 = s;
system("erase text.stack /Q");
text_write(s2);
}
else if(strstr("rT", action)){
text_read(s);
}
else if(strstr("help", action)){
help();
}
}
inline void binary_write(stack &s)
{
ofstream w ("binary.stack", ios::app | ios::binary);
if (s.head){
w << s.head->name << " " << s.head->raiting << endl;
s.head = s.head->next;
w.close();
binary_write(s);
}
else{
cout << "Done!" << endl;
}
w.close();
}
inline void binary_read(stack &s)
{
int count = 0;
ifstream r("binary.stack", ios::binary);
while(!r.eof()){
list *item = new stack;
r >> item->name >> item->raiting;
if(s.head){
item->next = s.head;
}
s.head = item;
if(!s.tail){
s.tail = s.head;
}
count++;
}
s.head = s.head->next;
cout << count-1 << " element was read from 'binary.stack'!" << endl;
r.close();
}
inline void text_write(stack &s)
{
ofstream w ("text.stack", ios::app);
if (s.head){
w << s.head->name << " " << s.head->raiting << endl;
s.head = s.head->next;
w.close();
text_write(s);
}
else{
cout << "Done!" << endl;
}
w.close();
}
inline void text_read(stack &s)
{
int count = 0;
ifstream r("text.stack");
while(!r.eof()){
list *item = new stack;
r >> item->name >> item->raiting;
if(s.head){
item->next = s.head;
}
s.head = item;
if(!s.tail){
s.tail = s.head;
}
count++;
}
s.head = s.head->next;
cout << count-1 << " element was read from 'text.stack'!" << endl;
r.close();
}
void help()
{
cout << endl << "Stack operations :" << endl;
cout << "\t* help - help" << endl;
cout << "\t* add - add element in stack" << endl;
cout << "\t* show <and amount> - print on screen elements of stack" << endl;
cout << "\t* clear - clear stack" << endl;
cout << "\t* rT - read stack from textfile" << endl;
cout << "\t* wT - write stack in textfile" << endl;
cout << "\t* rB - read stack from binaryfile" << endl;
cout << "\t* wB - write stack in binaryfile" << endl;
cout << "\t* close - close application" << endl << endl;
}
-
Контрольный пример
-
Список литературы:
-
C. Холзнер «Visual C++ 6»
-
Г. Шилдт «С++. Руководство для начинающих»
-
Выводы о проделанной работе
Навыки работы с базовыми списковыми структурами данных получены