Заглавная страница Избранные статьи Случайная статья Познавательные статьи Новые добавления Обратная связь FAQ Написать работу КАТЕГОРИИ: ТОП 10 на сайте Приготовление дезинфицирующих растворов различной концентрацииТехника нижней прямой подачи мяча. Франко-прусская война (причины и последствия) Организация работы процедурного кабинета Смысловое и механическое запоминание, их место и роль в усвоении знаний Коммуникативные барьеры и пути их преодоления Обработка изделий медицинского назначения многократного применения Образцы текста публицистического стиля Четыре типа изменения баланса Задачи с ответами для Всероссийской олимпиады по праву
Мы поможем в написании ваших работ! ЗНАЕТЕ ЛИ ВЫ?
Влияние общества на человека
Приготовление дезинфицирующих растворов различной концентрации Практические работы по географии для 6 класса Организация работы процедурного кабинета Изменения в неживой природе осенью Уборка процедурного кабинета Сольфеджио. Все правила по сольфеджио Балочные системы. Определение реакций опор и моментов защемления |
Заголовочный файл MyString.hСодержание книги Поиск на нашем сайте
#pragma once #include "io.h"
class MyString {char* s; int len; public: MyString(void); MyString (char* s); MyString (const MyString&); void assign (const MyString& t);
~MyString(void); void dispose (); MyString* copy(); int length(){return len;} int length()const {return len;} char* ToPchar(); int ToInt(); double ToDouble(); String* ToString();
int equal(const MyString& t); int cmp(const MyString& t);
int input(File fp); int input(); int output(File f); int output(); int input(TextBox * t);
};
12. Файл MyString.cpp #include "StdAfx.h" #include "MyString.h" #include "MyConvert.h" MyString::MyString(void) {s=0; len=0;}
MyString::~MyString(void) {dispose(); } void MyString::dispose() {delete [] s;}
MyString::MyString (char* ss) {if(ss==0){s=0; len=0;return;} s=new char[(len=strlen(s))+1]; strcpy(s,ss); } MyString::MyString(const MyString& t) {s=new char[(len=t.len)+1]; strcpy(s,t.s); } void MyString::assign (const MyString& t) {if(this==&t)return; char*ss=new char[(len=t.len)+1]; strcpy(ss,t.s); delete [] s; s=ss; } MyString* MyString::copy() {return new MyString(*this);}
char* MyString::ToPchar() {if(s==0)return 0; char* ss=new char[len+1]; strcpy(ss,s); return ss;}
int MyString::ToInt() {int i; MyConvert::copyto(&i,s); return i;}
double MyString::ToDouble() {double d; MyConvert::copyto(&d,s); return d;}
String* MyString::ToString() {return new String(s);}
int MyString::equal(const MyString& ss) {return strcmp(s,ss.s)==0;} int MyString::cmp(const MyString& ss) {return strcmp(s,ss.s);}
int MyString::input(File f) { if(::input(f,&s)) return len=strlen(s); return 0;}
int MyString::input() { if(::input(&s)) return len=strlen(s); return 0;} int MyString::input(TextBox * t) {if(::input(t,&s)) return len=strlen(s); return 0;} int MyString::output(File f) {return::output(f,s);} int MyString::output() {return::output(s);}
13. Заголовочный файл Record.h #pragma once #include "io.h" #include "compare.h" #include "MyString.h" #include "MyDate.h" class Record { MyString autor; MyString title; int number; int price; MyDate d; public: Record(); //выделяет память под класс Record //и инициализирует ее значениями по умолчанию Record(char*a,char*t,int n,int p,int d,int m,int y); Record(const Record&); ~Record(); Record* copy(); //coздает копию структуры Record в динамической памяти void dispose (); // Освобождает выделенную память под структур Record int validate(); // проверяет корректность данных int equal(const Record&); // функция, проверяющая равенство значений полей записей //Используется при поиске int cmp(const Record&); // функция, сравнивающая записи Используется при сортировки friend int CmpField(Record* a,Record* b,char*s);
int finput(File f); int input(File fp); int input(); int output(File f); void output();
void copyto(String* m[], int first=0); int input (TextBox* m[], int first=0); void output(TextBox* m[], int first=0); void output(ListView*list); }; Файл Record.cpp # #include "StdAfx.h" #include "item.h" #include "MyConvert.h" #include ".\validator.h"
Record::Record() // инициализирует значениями по умолчанию { number=0; price=0; } Record::Record(char*a,char*t,int n,int p,int d0,int m,int y):autor(a),title(t),d(d0,m,y) {number=n; price=p; чы} Record::Record(const Record& t) //coздает копию структуры Record в динамической памяти {autor.assign(t.autor); title.assign(t.title); d.assign(t.d); number=t. number; price=t.price; } Record* Record:: copy() {return new Record(*this);}
void Record::dispose () // Освобождает выделенную память {} Record::~Record() { dispose(); }
int Record::equal(const Record& r) { return ((r.autor.length()!=0)? autor.equal(r.autor):1)&& ((r.title.length()!=0)? title.equal(r.title):1)&& ((r.price!=0)? r.price == price:1) && ((r.number!=0)? r.number== number:1)&&
(((r.d.get_day()!=0) && (r.d.get_month()!=0) && (r.d.get_year()!=0))? d.equal(r.d):1);
} int Record::cmp(const Record& t) // функция, сравнивающая записи {int cond; MyString s1(t.autor); MyString s2(t.autor); if(s1.length()!=0&& (cond=autor.cmp(t.autor)))return cond; else if(s2.length()!=0&& (cond=title.cmp(t.title)))return cond; else return number-t.number; } int CmpField(Record* a,Record* b,char*s) {if (!strcmp(s,"autor")) return a->autor.cmp(b->autor); else if(!strcmp(s,"title")) return a->title.cmp(b->title); else if (!strcmp(s,"price")) return a->price-b->price; else if (!strcmp(s,"number")) return a->number-b->number; else if(!strcmp(s,"date")) return a->d.cmp(b->d); }
int Record::validate()// проверяет корректность данных { int a,b,c; a=IsLetters(autor.ToPchar()); b= IsLetters(title.ToPchar()); c=d.validate(); return a && b && c;}
int Record::input(File fp) {int state=1; state&=autor.input(fp); if(eof(fp)) return 0; state&=title.input(fp); if(eof(fp)) return 0; state&=::input(fp,&number); if(eof(fp)) return 0; state&=::input(fp,&price); if(eof(fp)) return 0; state&=d.input(fp); if(eof(fp)) return 0; state&=validate(); return state;}
int Record::input() {int state=1; ::output("autor"); state&=autor.input(); if(eof()) return 0; ::output("title"); state&=title.input(); if(eof()) return 0; ::output("number"); state&=::input(&number); if(eof()) return 0; ::output("price"); state&=::input(&price); if(eof()) return 0; ::output("data"); state&=d.input(); if(eof()) return 0; state&=validate(); return state;}
int Record::output(File f) { autor.output(f); title.output(f); return fprintf(f,"%d\t%d\n", number,price); d.output(f); } void Record::output() {output(stdout);}
int Record::input(TextBox* m[],int first) {int state=1; state&=autor.input(m[first++]); state&=title.input(m[first++]); state&=::input(m[first++],&number); state&=::input(m[first++],&price); state&=d.input(m[first], m[first+1], m[first+2]); state&=validate(); return state;} void Record::copyto(String* m[],int first) { m[first++]=autor.ToString(); m[first++]=title.ToString(); m[first++]=number.ToString(); m[first++]=price.ToString(); m[first++]=d.get_day().ToString(); m[first++]=d.get_month().ToString(); m[first++]=d.get_year().ToString(); } void Record::output(TextBox* m[],int first) {String* s[]=new String*[7]; copyto(s); MyConvert::copyto(m,s,7,first,0); }
void Record::output(ListView*list) { String* s[]=new String*[7]; copyto(s); list->Items->Add(new ListViewItem(s)); } 15. Заголовочный файл item.h #pragma once #include ".\record.h" typedef Record* T; typedef T* Iterator; Заголовочный файл vec.h #pragma once #include "item.h"
class vec { T* start; T* finish; public: vec(void){start=new T[100];finish=start+100;} vec(int sz){start=new T[sz];finish=start+sz;} ~vec(void){delete [] start;} void resize(int n) {T* _start; T* _finish; _start=_finish=new T[ finish-start+n]; T* i; for(i=start;i<=finish;i++) *_finish++=*i; delete [] start; start=_start; finish=_finish; } T* begin(void){return start;} T* end(void){return finish;} int get_size(void){return finish-start;} T& get_item(int i){return *(begin()+i);} }; Заголовочный файл Tabl.h #pragma once #include "item.h" #include "io.h" #include "compare.h" #include "vec.h"
class Tabl{ vec v; Iterator cur; T buf;
public:
Tabl(int sz=100,T buffer=0); ~Tabl(); void resize(int n); void clear(); void dispose (); Iterator begin(); Iterator end(); int length(); T get_item(int i);
Iterator insert(const T& item); Iterator erase(Iterator pos); int remove(const T& item);
void output(); int input(); int input(File f); void output(File f); void foutput(char* FileName); int finput(char* FileName);
Tabl* Query(Predicat& pred); int remove(Predicat &pred); void sort(); void sort(Cmp cmp);
void output(ListView*list);
};
18. Файл Tabl.cpp #include "stdafx.h" #include "validator.h" #include "Tabl.h"
T* Tabl::begin(){return v.begin();} T* Tabl::end() {return cur;} T Tabl::get_item(int i){return v.get_item(i);} int Tabl::length(){return cur-begin();}
Tabl::Tabl(int sz,T buffer):v(sz) {buf=buffer; cur=begin(); }
void Tabl::clear() {T* i; for(i=begin();i<cur;i++) {(*i)->dispose(); delete (*i);} cur=begin(); } void Tabl::dispose () {clear(); delete buf;} Tabl::~Tabl(){dispose ();}
T* Tabl::insert(const T& item) {if(length()>v.get_size()) v.resize(2*length());//return 0; *cur++=item->copy(); return cur; } T* Tabl::erase(T* pos) { T* i; (*pos)->dispose(); delete (*pos); for(i=pos;i<cur;i++) *i=*(i+1); cur--; return pos;}
int Tabl::remove(const T& item) {T* i; T* j=begin(); int n=0; for(i=begin();i<cur;i++) if(! (*i)->equal(*item)) *j++=*i; else { (*i)->dispose(); delete (*i); n++;} cur=j; return n; }
void Tabl::output() {T* i; for(i=begin();i!=end();i++) (*i)->output();}
int Tabl::input() {while(!eof()) if(buf->input ()) insert(buf); return length(); } int Tabl::input(File f) { while(!eof(f)) if(buf->input (f)) insert(buf); return length(); } void Tabl::output(File f) {T* i; for(i=begin();i!=end();i++) (*i)->output(f); } void Tabl::foutput(char* FileName) {File f; if ((f=fopen(FileName,"w"))==0) { ExeptionFopen(FileName); return;} output(f); fclose(f); }
int Tabl::finput(char* FileName) {int count; File f; if((f =fopen(FileName,"r"))==0) { ExeptionFopen(FileName); return 0;} count=input(f); fclose(f); return count; }
Tabl* Tabl::Query(Predicat& pred) {Tabl* rez=new Tabl(v.get_size()); T* i; for(i= begin();i<end();i++) if(pred.fun(*i)) rez->insert(*i); return rez; }
int Tabl::remove(Predicat &pred) {T* i; T* j=begin(); int n=0; for(i=begin();i<cur;i++) if(!(pred.fun(*i))) *j++=*i; else { (*i)->dispose(); delete i; n++;} cur=j; return n; } void Tabl::sort(){} void sort(Cmp cmp){}
void Tabl::output(ListView*list) {list->Items->Clear(); for(T* i=begin();i<end();i++) (*i)->output(list); } Заголовочный файл algo.h //алгоритмы #pragma once #include "item.h" #include "compare.h" Iterator find(const Iterator& first,const Iterator& last,const T& item); Iterator find(const Iterator& first,const Iterator& last,Predicat &pred); int replace(const Iterator& first,const Iterator& last,const T&Old,const T&New); void sort(const Iterator& first,const Iterator& last,Compare &Comp); Файл algo.cpp
#pragma once #include "stdafx.h" #include "algo.h" Iterator find(const Iterator& first,const Iterator& last,const T& item) {Iterator i; for(i=first;i<last;i++) if((*i)->equal(*item)) return i; return last; } Iterator find(const Iterator& first,const Iterator& last,Predicat &pred) {Iterator i; for(i=first;i<last;i++) if(pred.fun(*i)) return i; return last; } int replace(const Iterator& first,const Iterator& last,const T&Old,const T&New) {Iterator i;int count=0; for(i=first;i<last;i++) if((*i)->equal(*Old)) { (*i)->dispose(); *i=New->copy(); count++;} return count; } void sort(const Iterator& first,const Iterator& last,Compare &Comp) { Iterator i; Iterator j; T tmp;int k=0; for(i=first;i<last;i++,k++) { for(j=first+1;j<last-k;j++) if (Comp.cmp(*(j-1),*j)) {tmp=*(j-1);*(j-1)=*j;*j=tmp;} } } Заголовочный файл Compare.h
#pragma once class Record;
typedef int(*Cmp)(Record* a,Record* b, void* param); int CmpParam(Record* a, Record* b,void* param);
struct ParamSort { char* FieldName[3]; int DirectCond[3]; }; struct Compare{ public: void* param; Cmp f; int cmp(Record* a, Record* b) {return (*f)(a,b,param);} };
typedef bool(*Pr)(Record*,void* param); bool InRangePrice(Record* item, void* param);
struct InRange{ int MinValue,MaxValue; }; struct Predicat{ void* param; Pr f; bool fun(Record* item){return (*f)(item,param);} };
Файл реализации Compare.cpp #include "StdAfx.h" #include "compare.h" #include "Record.h"
int CmpParam(Record* a, Record* b,void* param) {ParamSort*p=(ParamSort*)param; if(CmpField(a,b,p->FieldName[0])!=0) if(p->DirectCond[0]==1) return CmpField(a,b,p->FieldName[0])>0; else return CmpField(a,b,p->FieldName[0])<0; else if(CmpField(a,b,p->FieldName[1])!=0) if(p->DirectCond[1]==1) return CmpField(a,b,p->FieldName[1])>0; else return CmpField(a,b,p->FieldName[1])<0; else if(CmpField(a,b,p->FieldName[2])!=0) if(p->DirectCond[2]==1) return CmpField(a,b,p->FieldName[2])>0; else return CmpField(a,b,p->FieldName[2])<0; } bool InRangePrice(Record* item, void* param) {InRange *p=(InRange *)param; Record r1(0,0,0,p->MinValue,0,0,0); Record r2(0,0,0,p->MaxValue,0,0,0); return CmpField(item,&r1,"price")>=0 && CmpField(item,&r2,"price")<=0; }
Заголовочный файл Form.h
#pragma once #include "stdafx.h" #include "exeptions.h" #include "chars.h" #include "Tabl.h" #include "FQuery2.h" #include "Sort.h" #include "algo.h" namespace Book_Lib_Stuct_2003 {T _current,_found; Iterator found;char* FileName; using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; public __gc class Form1: public System::Windows::Forms::Form {
//… public:Tabl* t; TextBox* m[]; private: int _foundNext, flag, SelectIndex;
private: System::Void Form1_Load(System::Object * sender, System::EventArgs * e) { _current=new Record; _found=new Record; t=new Tabl(100,_found); FileName=0; _foundNext=-1;flag=0; m=new TextBox*[7]; m[0]=textBox1;m[1]=textBox2;m[2]=textBox4; m[3]=textBox3; m[4]=textBox11;m[5]= textBox9; m[6]=textBox10; }
private: System::Void Create_Click(System::Object * sender, System::EventArgs * e) {t->clear(); listView1->Items->Clear(); this->Text="Без имени"; }
private: System::Void Insert_Click(System::Object * sender, System::EventArgs * e) { if(!_current->input(m)) {ExeptionEmpty();return;} t->insert(_current); t->output(listView1); }
private: System::Void Remove_Click(System::Object * sender, System::EventArgs * e) { _current->input(m); int i=t->remove(_current); if(i) {_current->output(m);t->output(listView1);} }
private: System::Void Find_Click(System::Object * sender, System::EventArgs * e) { _found->input(m); found=find(t->begin(),t->end(),_found); if(found!=t->end()) (*found)->output(m); else { ExeptionFound(); } }
private: System::Void FindNext_Click(System::Object * sender, System::EventArgs * e) {if(found==t->end()) return; found=find(++found,t->end(),_found); if(found!=t->end()) (*found)->output(m); else { ExeptionFound(); } }
private: System::Void Replace_Click(System::Object * sender, System::EventArgs * e) { if(flag==0) { if(!_found->input(m)){ExeptionEmpty();return;} flag=1; MessageBox::Show("Введите данные для замены и нажмите кнопку Заменить еще раз","Поиск"); return;} if(!_current->input(m)){ExeptionEmpty();return;} {flag=0; replace(t->begin(),t->end(),_found,_current); t->output(listView1); } } private: System::Void Clear_Click(System::Object * sender, System::EventArgs * e) { _current->dispose(); _current=new Record; _current->output(m); }
private: System::Void Query2_Click(System::Object * sender, System::EventArgs * e) {struct InRange p; FQuery2 *form= new FQuery2; form->getParam(&p); form->ShowDialog(); Predicat pred={(void*)&p,InRangePrice}; Tabl*q= t->Query(pred); q->output(listView1); }
private: System::Void Sort_Click(System::Object * sender, System::EventArgs * e) {struct ParamSort p={0,0,0,0,0,0}; TSort *form= new TSort; form->getParam(&p); form->ShowDialog(); Compare Comp ={(void*)&p,CmpParam}; sort(t->begin(),t->end(),Comp); t->output(listView1); }
private: System::Void Open_Click(System::Object * sender, System::EventArgs * e) {OpenFileDialog* fd = new OpenFileDialog(); fd->Title = "Open"; fd->Filter = "All files (*.*)|*.*|All files (*.*)|*.*"; if(fd->ShowDialog() == DialogResult::OK) { this->Text=fd->FileName; MyConvert::copyto(&FileName,fd->FileName); t->clear(); t->finput(FileName); t->output(listView1); } } private: System::Void MyClose_Click(System::Object * sender, System::EventArgs * e) { t->clear(); listView1->Items->Clear(); this->Text=""; }
private: System::Void Save_Click(System::Object * sender, System::EventArgs * e) {t->foutput(FileName); }
private: System::Void SaveAs_Click(System::Object * sender, System::EventArgs * e) {SaveFileDialog* fd = new SaveFileDialog(); fd->Title = "SaveAs"; fd->Filter = "All files (*.*)|*.*|All files (*.*)|*.*"; if(fd->ShowDialog() == DialogResult::OK) {this->Text=fd->FileName; MyConvert::copyto(&FileName,fd->FileName); t->foutput(FileName); } } private: System::Void Exit_Click(System::Object * sender, System::EventArgs * e) {this->Close();} private: System::Void listView1_SelectedIndexChanged(System::Object * sender, System::EventArgs * e) {int ind=listView1->SelectedIndices->get_Count()-1; if(ind!=-1) { int i=listView1->SelectedIndices->get_Item(ind); T s=t->get_item(i); s->output(m);} }
}; }
Приложение 3 Файл exeptions.h #pragma once void ExeptionLetters(char* str); void ExeptionInt(char* str); void ExeptionFloat(char* str); void ExeptionRange(double d,double min,double max); void ExeptionFopen(char* str); void ExeptionFound(); void ExeptionEmpty(); void ExeptionInvalidValue(char* str); Файл exeptions.cpp
#include "stdafx.h" #include "exeptions.h" using namespace System; using namespace System::Windows::Forms;
void ExeptionLetters(char* str) {String^ s=gcnew String(str); s=String::Concat("\nString\t",s,"\t must include inglish letters\n"); MessageBox::Show(s,"ExeptionLetters "); return; }
void ExeptionInt(char* str) {String^ s=gcnew String(str); s=String::Concat("\nString\t",s,"\t must include letters of digits\n"); MessageBox::Show(s,"ExeptionInt ");}
void ExeptionFloat(char* str){}
void ExeptionRange(double d,double min,double max) {String^ s1=d.ToString(); String^ s2=min.ToString(); String^ s3=max.ToString(); s1=String::Concat("\n Value\t",s1,"\t must be latter then ",s2,"and must be greater then",s3); MessageBox::Show(s1,"ExeptionRange");}
void ExeptionFopen(char* str) {String^ s=gcnew String(str); s=String::Concat("\nFile\t",s,"\t open error\n"); MessageBox::Show(s,"ExeptionFopen");} void ExeptionInvalidValue(char* str) {String^ s=gcnew String(str); s=String::Concat("\nValue\t",s,"\t Invalid \n"); MessageBox::Show(s,"Invalid Value");} void ExeptionFound() {MessageBox::Show("Просмотр закончен. Искомый элемент не найден" ,"Поиск");} void ExeptionEmpty() {MessageBox::Show("Поля ввода не должны быть пустыми" ,"Input");} Файл validator.h #pragma once #include "exeptions.h" int IsLetters(char* s); int IsInt(char* s); int IsFloat(char* s); int InRangeValue(double d,double min,double max);
Файл validator.cpp #include "stdafx.h" #include "validator.h"
int IsLetters(char* s) {if(s==0)return 0; for(;*s!='\0' && toupper(*s)>='A' && toupper(*s)<='Z';s++) ; if (*s!='\0') {ExeptionLetters(s); return 0;} return 1;}
int IsInt(char* s) {if(s==0)return 0; for(;*s!='\0' && *s>='0' && *s<='9';s++) ; if (*s!='\0') {ExeptionInt(s); return 0;} return 1;}
int IsFloat(char* s){if(s==0)return 0; return 1;}
int InRangeValue(double d,double min,double max) {if(d<min|| d>max) {ExeptionRange(d,min,max); return 0;} return 1;} Файл win.h int ToChar(char* out,wchar_t* in);
Файл win.cpp #include "StdAfx.h" #using <mscorlib.dll> #include <windows.h> int ToChar(char* out,wchar_t* in) {return WideCharToMultiByte(CP_ACP, 0, in, 1,out, 1, NULL, NULL); }
Файл MyConvert.h #pragma once using namespace System; using namespace System::Windows::Forms; class MyConvert { public:
static int copyto(char** ss,char buf[]); static int copyto(int* i,char buf[]); static int copyto(double* d,char buf[]); static int copyto(char* s, int i); static int copyto(char* s,double d); static int copyto(char* buf,String^ S,int count=0); static int copyto(char** str,String^ S); static int copyto(String^ &S,char* buf); static int copyto(char* m[],cli::array<String ^ >^ s,int count,int first_s=0,int first_m=0); static int copyto(cli::array<String ^ >^ m,char* s[],int count,int first_s=0,int first_m=0); static int copyto(cli::array<TextBox^>^ m,char* s[],int count,int first_s=0,int first_m=0); static int copyto(char* m[],cli::array<TextBox^>^ s,int count,int first_s=0,int first_m=0); static int copyto(cli::array<TextBox^>^ m,cli::array<String ^ >^s,int count,int first_s=0,int first_m=0); static int copyto(cli::array<String ^ >^m, cli::array<TextBox^>^ s, int count,int first_s=0,int first_m=0); MyConvert(void); public: ~MyConvert(void); };
Файл MyConvert.cpp #include "StdAfx.h" #include "MyConvert.h" #include "validator.h" #include "win.h"
int MyConvert::copyto(char** s,char buf[]) { //if(buf==0)return 0; delete [](*s); *s=new char[strlen(buf)+1]; strcpy(*s,buf); return 1;}
int MyConvert::copyto(int* i,char buf[]) {if(IsInt(buf)) *i=atoi(buf) ; else return 0; return 1;} int MyConvert::copyto(double* i,char buf[]) {return 1;} int MyConvert::copyto(char* s, int i) {return itoa(i,s,10)? 1: 0; } int MyConvert::copyto(char* s,double d) {return gcvt(d,10,s)? 1: 0; }
//#include "win.h"
int MyConvert::copyto(char* buf,System::String^ S,int count) {int i, state; for(i=0;i<S->Length;i++){ if(count && i>count) break; wchar_t t=S->default[i]; state=ToChar(&buf[i],&t); //state=WideCharToMultiByte(CP_ACP, 0, &t, 1, &buf[i], 1, NULL, NULL); } buf[i]='\0'; return state;}
int MyConvert::copyto(char** str,System::String^ S) { delete [](*str); *str=new char [S->Length+1]; return MyConvert::copyto(*str,S); } int MyConvert::copyto(System::String^ &S,char* buf) {S=gcnew System::String(buf); return 1;}
int MyConvert::copyto(char* m[],cli::array<String ^ >^ s,int count,int first_s,int first_m) { //if(s==0)return 0; while(count-->0) { copyto(&m[first_m],s[first_s]); ++first_m; ++first_s;} return 1; } int MyConvert::copyto(cli::array<String ^ >^ m,char* s[],int count,int first_s,int first_m) { if(s==0)return 0; while(count-->0) {//copyto(m[first_m],s[first_s]); m[first_m]=gcnew System::String(s[first_s]); ++first_m; ++first_s;} return 1; } int MyConvert::copyto(cli::array<TextBox^>^ m,char* s[],int count,int first_s,int first_m) {if(s==0)return 0; while(count-->0) {m[first_m]->Text=gcnew String(s[first_s]); ++first_m; ++first_s; } return 1; } int MyConvert::copyto(char* m[],cli::array<TextBox^>^ s,int count,int first_s,int first_m) {//if(s==0)return 0; while(count-->0) { copyto(&m[first_m],s[first_s]->Text); ++first_m; ++first_s; } return 1; } int MyConvert::copyto(cli::array<TextBox^>^ m,cli::array<String ^ >^s,int count,int first_s,int first_m) { //if(s==0)return 0; while(count-->0) {m[first_m]->Text=s[first_s]; ++first_m; ++first_s; } return 1; } int MyConvert::copyto(cli::array<String ^ >^m, cli::array<TextBox^>^ s, int count,int first_s,int first_m) { //if(s==0)return 0; while(count-->0){m[first_m]=s[first_s]->Text; ++first_m; ++first_s; } return 1; } MyConvert::MyConvert(void) { }
MyConvert::~MyConvert(void) { } Файл Obj.h #pragma once class MyString; class Obj{ public: virtual ~Obj(){} virtual MyString* ToMyString()=0; virtual Obj* copy()=0; virtual void dispose ()=0; virtual int equal(const Obj&)=0; virtual int cmp(const Obj&)=0; };
Файл io.h #pragma once #include "Obj.h" #include "MyConvert.h" typedef FILE* File; int eof(File fp); int eof(); void clear(File fp); void clear(); int input(File fp,char* s); int input(File fp,char* s,int lim); int input(File fp,char** s); int input(File fp,int* i); int input(File fp,double* i); int input(char* s,int* i); int input(char* s,double* i); int input(char* s); int input(char** s); int input(int* i); int input(double* d);
int output(char* s); int output(File fp,char* s); int output(File fp,int i); int output(char* s,int i); int output(char* s,double d);
using namespace System; using namespace System::Windows::Forms; int input(TextBox^ t,char* s,int count); int input(TextBox^ t,char** s); int input(TextBox^ t,int *i);
class InOut:public Obj{ public: virtual int input(File fp)=0; virtual int input()=0; virtual int output(File f)=0; virtual int output()=0;
virtual int input (char* m[], int first=0)=0; virtual int output (char* m[], int first=0)=0;
int input (cli::array<TextBox^>^ m, int count, int first=0); int output (cli::array<TextBox^>^ m, int count, int first=0); int output(ListView^ lis, int count); }; Файл io.cpp
#include "stdafx.h" #include "io.h" #include "MyConvert.h" #define MAX 256 char buf[MAX]; using namespace std; int eof(FILE* fp){return feof(fp);} int eof(){return feof(stdin); } void clear(FILE* fp){rewind(fp);} void clear(){rewind(stdin); }
int input(File fp,char* s) {int state=fscanf(fp,"%s",s); return state && state!=EOF; } int input(FILE* fp,char** s) { return input(fp,buf) && MyConvert::copyto(s,buf); }
int output(FILE* fp,char* s) {return fprintf(fp,"%s\n",s);} int output(File fp,int i) {return fprintf(fp,"%d\n",i);} int output(char* s,int i) {return sprintf(s,"%d",i);} int output(char* s,double d) {return sprintf(s,"%f",d);}
int input(FILE* fp,int* i) {return input(fp,buf) && MyConvert::copyto(i,buf);}
int input(FILE* fp,double* i) {return 1;}
int input(char* s) {return input(stdin,s);} int input(char** s) {return input(stdin,s);} int input(int* i) {return input(stdin,i);} int input(double* d){return input(stdin,d);} int output(char* s) {return output(stdout,s);}
int input(FILE* fp,char* s,int lim) { int c; while((c=getc(fp))!=EOF && isspace(c)) ; if(c==EOF) return 0; *s++=c;--lim; while(--lim>0 && (c=getc(fp))!=EOF &&!isspace(c)) *s++=c; *s='\0'; return (c== EOF||lim==0)? 0:1; } using namespace System; using namespace System::Windows::Forms;
int input(TextBox^ t,char* s,int count) {return MyConvert::copyto(s,t->Text,count); } int input(TextBox^ t,char** s) { return input(t,buf,MAX) && MyConvert::copyto(s,buf); }
int input(TextBox^ t,int *i) {return input(t,buf,MAX) && MyConvert::copyto(i,buf);}
class Buff{ char** ms; int count; public: char**get(){return ms;} Buff(int _count,int max) { ms=new char*[count=_count]; for(int i=0;i<count;i++) ms[i]=new char[max]; } ~Buff() {for(int i=0;i<count;i++) delete [] ms[i]; delete []ms; } }; int InOut::input (cli::array<TextBox^>^ m, int count, int first) {Buff b(count,MAX); MyConvert::copyto(b.get(),m,count,first,0); return input(b.get()); } int InOut::output (cli::array<TextBox^>^ m, int count, int first) {Buff b(count,MAX); int state= output(b.get()); MyConvert::copyto(m,b.get(),count,0,first); return state; } int InOut::output(ListView^list, int count) {Buff b(count,MAX); int state=output(b.get()); cli::array<String ^ >^m=gcnew cli::array< System::String^ >(count); //String* m[]=new String*[count]; MyConvert::copyto(m,b.get(),count); list->Items->Add(gcnew ListViewItem(m)); return state; } ФайлMyString.h #pragma once #include "io.h"
class MyString: public InOut {char* s; int len; public: MyString(void); MyString (char* s); MyString (const MyString&); void assign (const MyString& t);
~MyString(void); void dispose (); MyString* copy(); int length(){return len;} int length()const {return len;} char* ToPchar(); int ToInt(); double ToDouble(); String^ ToString(); MyString* ToMyString();
int equal(const MyString& t); int cmp(const MyString& t); int equal(const Obj& t); int cmp(const Obj& t);
int input (char* m[], int first=0); int output(char* m[], int first=0); int input(File fp); int input(); int output(File f); int output();
int input(TextBox^ t);
};
ФайлMyString.cpp #include "StdAfx.h" #include "MyString.h" #include "MyConvert.h" MyString::MyString(void) {s=0; len=0;}
MyString::~MyString(void) {dispose(); } void MyString::dispose() {delete [] s;}
MyString::MyString (char* ss) {if(ss==0){s=0; len=0;return;} s=new char[(len=strlen(ss))+1]; strcpy(s,ss); } MyString::MyString(const MyString& t) {s=new char[(len=t.len)+1]; strcpy(s,t.s); } void MyString::assign (const MyString& t) {if(this==&t)return; char*ss=new char[(len=t.len)+1]; strcpy(ss,t.s); delete [] s; s=ss; } MyString* MyString::copy() {return new MyString(*this);}
char* MyString::ToPchar() {if(s==0)return 0; char* ss=new char[len+1]; strcpy(ss,s); return ss;} MyString* MyString::ToMyString(){return new MyString(*this);} int MyString::ToInt() {int i; MyConvert::copyto(&i,s); return i;}
double MyString::ToDouble() {double d; MyConvert::copyto(&d,s); return d;}
String^ MyString::ToString() {return gcnew String(s);}
int MyString::equal(const MyString& ss) {return strcmp(s,ss.s)==0;} int MyString::cmp(const MyString& ss) {return strcmp(s,ss.s);}
int MyString::equal(const Obj& t) {return equal((const MyString&)t);} int MyString:: cmp(const Obj& t) {return cmp((const MyString&)t);}
int MyString::input(File f) { if(::input(f,&s)) return len=strlen(s); return 0;}
int MyString::input() { if(::input(&s)) return len=strlen(s); return 0;} int MyString::input(TextBox^ t) {if(::input(t,&s)) return len=strlen(s); return 0;} int MyString::output(File f) {return::output(f,s);} int MyString::output() {return::output(s);} int MyString::input (char* m[], int first) {char*ss=new char[(len=strlen(m[first]))+1]; strcpy(ss,m[first]); delete [] s; s=ss; return len;} int MyString::output(char* m[], int first) {delete [] m[first]; m[first]=new char[len+1]; strcpy(m[first],s); return len;} Файл MyDate.h #pragma once #include "io.h" #include "MyString.h" class MyDate:public InOut { int day,month,year; static int daytab[2][13]; static char* MonthName[13]; static char* DayNames[8]; public: MyDate(void); int get_day(){return day;} int get_month(){return month;} int get_year(){return year;} int get_day()const {return day;} int get_month()const {return month;} int get_year()const {return year;} public: ~MyDate(void); MyDate(int d,int m,int y); MyDate (char* s); MyDate (const MyDate&); void assign (const MyDate& t); void dispose (); MyDate* copy(); int validate(); static int vis(int y) { return ((!(y%4))&&(y%100)||(!(y%400))); } char* ToPchar(); String^ ToString(); MyString* ToMyString(){return new MyString(ToPchar());}
int equal(const MyDate& t); int cmp(const MyDate& t); int equal(const Obj& t); int cmp(const Obj& t);
int input (char* m[], int first=0); int output(char* m[], int first=0); int input(File fp); int input(); int output(File f); int output();
int input(TextBox^ t1, TextBox^ t2, TextBox^ t3);
};
Файл MyDate.cpp #include "StdAfx.h" #include "MyDate.h" #include "exeptions.h" #include "MyConvert.h" int MyDate::daytab[2][13]={{0,31,28,31,30,31,30,31,31,30,31,30,31},{0,31,29,31,30,31,30,31,31,30,31,30,31}}; char* MyDate::MonthName[13]={"Wrong month","January","February","March","April","May","June","July","August","September","October","November","December"}; char* MyDate::DayNames[8]={"Wrong day","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}; MyDate::MyDate(void) {day=month=year=0; }
MyDate::~MyDate(void) { } MyDate::MyDate(int d,int m,int y) { day=d; month=m; year=y; if(!validate()) ExeptionInvalidValue("MyDate");
} int MyDate::validate() { return (year>0&&month>0&&month<=12&&day>0&&day<=daytab[vis(year)][month]); } MyDate::MyDate (char* s){} MyDate::MyDate (const MyDate& d) {day=d.day; month=d.month; year=d.year;} void MyDate::assign (const MyDate& d) {day=d.day; month=d.month; year=d.year;} void MyDate::dispose (){} MyDate* MyDate::copy() {return new MyDate();} char* MyDate::ToPchar() {char s[256],buf[256],*s1; s[0]='\0'; itoa(day,buf,10); strcat(s,buf); strcat(s,"."); itoa(month,buf,10); strcat(s,buf); strcat(s,"."); itoa(year,buf,10); strcat(s,buf); s1=new char[strlen(s)+1]; strcpy(s1,s); return s1;} String^ MyDate::ToString() {return gcnew String(ToPchar());}
int MyDate::equal(const MyDate& d) {return day==d.day && month==d.month && year==d.year;}
int MyDate::cmp(const MyDate& d) {if(year!=d.year)return year-d.year; else if(month!=d.month)return month-d.month; else return day-d.day; } int MyDate::equal(const Obj& t) {return equal((const MyDate&)t);} int MyDate::cmp(const Obj& t) {return cmp((const MyDate&)t);}
int MyDate::input (char* m[], int first) {MyConvert::copyto(&day,m[first++]); MyConvert::copyto(&month,m[first++]); MyConvert::copyto(&year,m[first++]); return 3;} int MyDate::output(char* m[], int first) {MyConvert::copyto(m[first++],day); MyConvert::copyto(m[first++],month); MyConvert::copyto(m[first++],year); return 3;}
int MyDate::input(File fp) {int state=1; state*=::input(fp,&day); if(eof(fp)) return 0; state*=::input(fp,&month); if(eof(fp)) return 0; state*=::input(fp,&year); if(eof(fp)) return 0; return state;} int MyDate::input() {int state=1; ::output("day"); state*=::input(&day); if(eof()) return 0; ::output("month"); state*=::input(&month); if(eof()) return 0; ::output("year"); state*=::input(&year); if(eof()) return 0; return state;} int MyDate::output(File f) {return fprintf(f,"%d\t%d\t%d\n", day,month,year); } int MyDate::output() {return output(stdin);} int MyDate::input(TextBox^ t1, TextBox^ t2, TextBox^ t3) {int state=1; state*=::input(t1,&day); state*=::input(t2,&month); state*=::input(t3,&year); return state;}
Файл compare.h #pragma once #include "Obj.h"
struct ParamSort { char* FieldName[3]; int DirectCond[3]; ParamSort() {for(int i=0;i<3;i++) {FieldName[i]=0;DirectCond[i]=0;} } }; struct InRange { Obj* Min,*Max; char*s; InRange(Obj* m1, Obj* m2,char* s0): Min(m1),Max(m2), s(s0){} };
Файл Record.h #pragma once #include "compare.h" #include "io.h" class Record: public InOut {public: virtual int CmpField(const Obj& obj,char*s)=0; virtual int CountFields()=0; //virtual char** NamesFields()=0; int InRangeValue(InRange* param); static int CmpParamSort(Obj* a, Obj* b,ParamSort* p); public: Record(void); public: ~Record(void);};
class Compare{ public: virtual int cmp(Obj* a, Obj* b)=0; }; class Compare1: public Compare { ParamSort* param; public: int cmp(Obj* a, Obj* b) {return Record::CmpParamSort(a,b,param);} Compare1(ParamSort* p):param(p){} };
class Predicat{ public: virtual bool fun(Obj* item)=0; }; class Predicat1: public Predicat{
InRange* param;
public: bool fun(Obj* item){return ((Record*)item)->InRangeValue(param);} Predicat1 (InRange* p):param(p){} };
Файл Record.cpp #include "StdAfx.h" #include "Record.h"
int Record::InRangeValue(InRange* param) {return CmpField((Obj&)(*(param->Min)),param->s)>=0 && CmpField((Obj&)(*(param->Max)),param->s)<=0;} int Record::CmpParamSort(Obj* aa, Obj* bb,ParamSort* p) { Record* a= (Record*)aa; Record* b= (Record*)bb; if(a->CmpField(*b,p->FieldName[0])!=0) if(p->DirectCond[0]==1) return a->CmpField(*b,p->FieldName[0])>0; else return a->CmpField(*b,p->FieldName[0])<0; else if(a->CmpField(*b,p->FieldName[1])!=0) if(p->DirectCond[1]==1) return a->CmpField(*b,p->FieldName[1])>0; else return a->CmpField(*b,p->FieldName[1])<0; else if(a->CmpField(*b,p->FieldName[2])!=0) if(p->DirectCond[2]==1) return a->CmpField(*b,p->FieldName[2])>0; else return a->CmpField(*b,p->FieldName[2])<0; } Record::Record(void) { }
Record::~Record(void) { } Файл Book.h #pragma once #include "io.h" #include "Record.h" #include "MyString.h" #include "MyDate.h" class Book:public Record { MyString autor; MyString title; int number; int price;
public: Book(); //выделяет память под класс Record //и инициализирует ее значениями по умолчанию Book(char*a,char*t,int n,int p); Book(const Book&); ~Book(); MyString* ToMyString(){return new MyString("Book");} Book* copy(); //coздает копию структуры Record в динамической памяти void dispose (); // Освобождает выделенную память под структур Record int validate(); // проверяет корректность данных int equal(const Book&); // функция, проверяющая равенство значений полей записей //Используется при поиске int cmp(const Book&); // функция, сравнивающая записи Используется при сортировки friend int CmpField(Book* a,Book* b,char*s); int CmpField(const Obj& obj,char*s); int CountFields() {return 4;} int equal(const Obj&); int cmp(const Obj&);
int finput(File f); int input(File fp); int input(); int output(File f); int output();
int input (char* m[], int first=0); int output(char* m[], int first=0); };
Файл Book.cpp #include "StdAfx.h" #include "Book.h" #include "MyConvert.h" #include ".\validator.h" Book::Book() // инициализирует значениями по умолчанию { number=0; price=0; } Book::Book(char*a,char*t,int n,int p):autor(a),title(t) { number=n; price=p;
} Book::Book(const Book& t) //coздает копию структуры Book в динамической памяти {autor.assign(t.autor); title.assign(t.title); number=t. number; price=t.price; }
Book* Book:: copy() {return new Book(*this);}
void Book::dispose () // Освобождает выделенную память {}
Book::~Book() { dispose(); }
int Book::equal(const Book& r) { return ((r.autor.length()!=0)? autor.equal(r.autor):1)&& ((r.title.length()!=0)? title.equal(r.title):1)&& ((r.price!=0)? r.price == price:1) && ((r.number!=0)? r.number== number:1) ;
} int Book::cmp(const Book& t) // функция, сравнивающая записи {int cond;
MyString s1(t.autor); MyString s2(t.autor); if(s1.length()!=0&& (cond=autor.cmp(t.autor)))return cond; else if(s2.length()!=0&& (cond=title.cmp(t.title)))return cond; else return number-t.number; } int Book::equal(const Obj& t) {return equal((const Book&) t);} int Book::cmp(const Obj& t) {return cmp((const Book&) t);}
int CmpField(Book* a,Book* b,char*s) {if (!strcmp(s,"autor")) return a->autor.cmp(b->autor); else if(!strcmp(s,"title")) return a->title.cmp(b->title); else if (!strcmp(s,"price")) return a->price-b->price; else if (!strcmp(s,"number")) return a->number-b->number; } int Book::CmpField(const Obj& obj,char*s) {return::CmpField(this,(Book*)&obj,s);}
int Book::finput(File f) { int state=autor.input(f); state&=title.input(f); return state; } int Book::validate()// проверяет корректность данных { int a,b; char* s1=autor.ToPchar(); char* s2=title.ToPchar(); a=IsLetters(s1); if(!a) return 0; b=IsLetters(s2); if(!b) return 0;
return 1;}
int Book::input(File fp) {int state=1; state*=autor.input(fp); if(eof(fp)) return 0; state*=title.input(fp); if(eof(fp)) return 0; state*=::input(fp,&number); if(eof(fp)) return 0; state*=::input(fp,&price); if(eof(fp)) return 0; state*=validate(); return (state==0)? 0: 4;}
int Book::input() {int state=1; ::output("autor"); state*=autor.input(); if(eof()) return 0; ::output("title"); state*=title.input(); if(eof()) return 0; ::output("number"); state*=::input(&number); if(eof()) return 0; ::output("price");
state*=validate(); return (state==0)? 0: 4;}
int Book::output(File f) { autor.output(f); title.output(f); ::output(f,number); ::output(f,price); return 4; } int Book::output() {return output(stdout);}
int Book::input (char* m[], int first) {int state=1; state*=autor.input(m,first++); state*=title.input(m,first++); state*=MyConvert::copyto(&number,m[first++]); state*=MyConvert::copyto(&price,m[first++]); state*=validate(); return (state==0)? 0: 4;} int Book::output(char* m[], int first) {m[first++]=autor.ToPchar(); m[first++]=title.ToPchar(); ::output(m[first++],number); ::output(m[first++],price); return 4; } Файл Record.h
#pragma once #include "io.h" #include "Record.h" #include "MyString.h" #include "MyDate.h" class Reader:public Record { MyString name; MyString address; int number; int telephon; public: Reader(); //выделяет память под класс Reader //и инициализирует ее значениями по умолчанию Reader(char*n,char*a,int nn,int t); Reader(const Reader&); ~Reader(); MyString* ToMyString(){return new MyString("Reader");} Reader* copy(); //coздает копию структуры Reader в динамической памяти void dispose (); // Освобождает выделенную память под структур Reader int validate(); // проверяет корректность данных int equal(const Reader&); // функция, проверяющая равенство значений полей записей //Используется при поиске int cmp(const Reader&); // функция, сравнивающая записи Используется при сортировки friend int CmpField(Reader* a,Reader* b,char*s); int CmpField(const Obj& obj,char*s); int CountFields(){return 4;} int equal(const Obj&); int cmp(const Obj&);
int finput(File f); int input(File fp); int input(); int output(File f); int output();
int input (char* m[], int first=0); int output(char* m[], int first=0);
}; Файл Record.cpp #include "StdAfx.h" #include "Reader.h" #include "MyConvert.h" #include ".\validator.h" Reader::Reader() // инициализирует значениями по умолчанию { number=0; telephon=0; } Reader::Reader(char*n,char*a,int nn,int t):name(n),address(a) {number=nn; telephon=t;
} Reader::Reader(const Reader& t) //coздает копию структуры Reader в динамической памяти {name.assign(t.name); address.assign(t.address); number=t. number; telephon=t.telephon; }
Reader* Reader:: copy() {return new Reader(*this);}
void Reader::dispose () // Освобождает выделенную память {}
Reader::~Reader() { dispose(); }
int Reader::equal(const Reader& r) { return ((r.name.length()!=0)? name.equal(r.name):1)&& ((r.address.length()!=0)? address.equal(r.address):1)&& ((r.telephon!=0)? r.telephon == telephon:1) && ((r.number!=0)? r.number== number:1) ;
} int Reader::cmp(const Reader& t) // функция, сравнивающая записи {int cond;
MyString s1(t.name); MyString s2(t.name); if(s1.length()!=0&& (cond=name.cmp(t.name)))return cond; else if(s2.length()!=0&& (cond=address.cmp(t.address)))return cond; else return number-t.number; } int Reader::equal(const Obj& t) {return equal((const Reader&) t);} int Reader::cmp(const Obj& t) {return cmp((const Reader&) t);}
int CmpField(Reader* a,Reader* b,char*s) {if (!strcmp(s,"name")) return a->name.cmp(b->name); else if(!strcmp(s,"address")) return a->address.cmp(b->address); else if (!strcmp(s,"telephon")) return a->telephon-b->telephon; else if (!strcmp(s,"number")) return a->number-b->number; } int Reader::CmpField(const Obj& obj,char*s) {return::CmpField(this,(Reader*)&obj,s);} int Reader::finput(File f) { int state=name.input(f); state&=address.input(f); return state; } int Reader::validate()// проверяет корректность данных { int a,b; a=IsLetters(name.ToPchar()); b= IsLetters(address.ToPchar()); return a && b;}
int Reader::input(File fp) {int state=1; state*=name.input(fp); if(eof(fp)) return 0; state*=address.input(fp); if(eof(fp)) return 0; state*=::input(fp,&number); if(eof(fp)) return 0; state*=::input(fp,&telephon); if(eof(fp)) return 0; |
|
| Поделиться: |
Познавательные статьи:
Последнее изменение этой страницы: 2016-07-11; просмотров: 495; Нарушение авторского права страницы; Мы поможем в написании вашей работы!
infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 216.73.216.119 (0.009 с.)