Skip to content

Instantly share code, notes, and snippets.

@LifeMoroz
Created December 2, 2012 18:45
Show Gist options
  • Save LifeMoroz/4190396 to your computer and use it in GitHub Desktop.
Save LifeMoroz/4190396 to your computer and use it in GitHub Desktop.
Last lab
#include <iostream>
#include <fstream>
#include "math.h"
#include "windows.h"
#include <iomanip>
#include <conio.h>
#include <stdio.h>
using namespace std;
struct en_rus
{
int n; //позиция в словаре
char wEn[31]; //английски
char wRus[31]; //русский
en_rus* next;
};
struct listD
{
en_rus* first;
en_rus* last;
};
bool chk_empty(listD l) //проверка на пустоту
{
return (l.first==NULL);
}
void en_rus_in(listD &l, char* En, char* Rus, int pos);
void en_rus_del(listD &l, en_rus* c);
void clear(listD &l)
{
en_rus* g;
while (l.first != NULL)
{
g=l.first->next;
en_rus_del(l,l.first);
l.first=g;
}
}
////////////////////////////////////////////
en_rus* h; //для операции delete
////////////////////////////////////////////
int searchEn(listD list, char* x, bool f=true);//Бинарный поиск
int searchRus(listD list, char* x, bool f=true);//Пошаговый поиск
void add(listD &list);
void delet(listD &list);
int read(listD &list);
void print(listD list);
void menu(listD &Dict);
void out(listD dict);
void translate(listD list);
////////////////////////////////////////////
int main()
{
setlocale(0,"rus");
listD dict;
dict.first=NULL;
int n;
n=read(dict);
if (n==0)
{
cout<<"Фаил пуст, для продолжения работа добавьте хотя бы 1 запись"<<endl;
cout<<"File do not have any records, pls add it"<<endl;
add(dict);
}
menu(dict);
system("pause");
return 0;
}
////////////////////////////////////////////
void menu(listD &Dict)
{
while(1)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute ( hStdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
cout<<"1. Вывести словарь на экран"<<endl;
cout<<"2. Добавить запись"<<endl;
cout<<"3. Удалить запись"<<endl;
cout<<"4. Перевести слово"<<endl;
cout<<"5. Записать изменения в файл"<<endl;
cout<<"6. Синхронизировать со словарем"<<endl;
cout<<"7. Очистить экран вывода"<<endl;
cout<<"8. Завершить программу"<<endl;
int g;
cin>>g;
switch (g)
{
case 1: print(Dict); break;
case 2: add(Dict); break;
case 3: delet(Dict); break;
case 4: translate(Dict); break;
case 5: out(Dict); break;
case 6: clear(Dict);read(Dict);
case 7: system("cls"); break;
case 8: exit(0); break;
default:
cout<<"Нет такой команды"<<endl;
system("pause");
system("cls");
}
}
}
void print(listD dict)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
while (dict.first != NULL)
{
SetConsoleTextAttribute ( hStdout, FOREGROUND_RED | FOREGROUND_GREEN);
cout<<setw(4)<<dict.first->n;
SetConsoleTextAttribute(hStdout,FOREGROUND_GREEN);
cout<<setw(16)<< dict.first->wEn;
SetConsoleTextAttribute ( hStdout, FOREGROUND_RED | FOREGROUND_BLUE );
cout<<setw(16)<< dict.first->wRus<<endl;
dict.first = dict.first->next;
}
SetConsoleTextAttribute ( hStdout, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE );
}
int chk_lang(char* x)
{
int y;
if (x[0]>='a' && x[0]<='z') {y=1;}
else if (x[0]>='а' && x[0]<='я') {y=0;}
else if (x[0]>='0' && x[0]<='9') {y=-1;}
else
{
cout<<"Ошибка ввода"<<endl;
exit(3);
}
return y;
}
void en_rus_in(listD &l, char* En, char* Rus, int pos)
{
en_rus* c = new en_rus();
int i=0;
strcpy_s(c->wEn,31,En);
strcpy_s(c->wRus,31,Rus);
if (l.first==NULL || pos>l.last->n)
{
c->next = NULL;
if (l.first!=NULL)
c->n=(l.last->n)+1;
else c->n=1;
if (chk_empty(l))
l.first = c;
else
l.last->next = c;
l.last = c;
return;
}
en_rus *b, *a;
b=l.first;
if (pos!=0)
{
for(int i=1; i<pos; i++)
{
a=b;
b=b->next;
}
a->next=c;
c->n=pos;
}
else c->n=1;
c->next=b;
while (b != NULL)
{
b->n++;
b=b->next;
}
}
void en_rus_del(listD &l, en_rus* c)
{
if (c == l.first)
{
l.first = c->next;
return;
}
en_rus* r = new en_rus();
r = l.first;
while (r->next != c)
r = r->next;
r->next = c->next;
delete c;
while (r->next != NULL)
{
r=r->next;
r->n--;
}
cout<<"Выполнено! \\ Complete!"<<endl;
}
int read(listD &list)
{
ifstream inFile; // Входной файловый поток
// Открыть файл source и связать его с потоком inFile:
inFile.open("Dictionary.txt", ios::app);
if (!inFile) // Проверить правильность открытия файла
{
cerr << "\nОшибка при открытии файла словаря, проверьте наличие словаря в корне";
exit(1); // Завершение программы
}
int n=1;
while(!inFile.eof())
{
char a[100], *b, *b1;
int k=0;
inFile.getline(a,99,'\n');
//cout<<"Строка "<< n<<" "<< a<<endl;
if (inFile.eof()) break;
b=strtok(a,".");
k=atoi(b);
b=strtok(NULL,".");
b1=strtok(NULL,".");
en_rus_in(list, b, b1, n);
n++;
}
n--;
inFile.close();
return n;
}
void add(listD &list)
{
en_rus ad;
cout<<"Вы выбрали функцию добавить слово \\ You have chosen \"add word\""<<endl;
cout<<"Введите слово на английском языке \\ Write your word EN"<<endl;
cin >> ad.wEn;
if (ad.wEn[0]>'z' || ad.wEn[0]<'a' )
{
cout<<"Ошибка ввода";
return;
}
int k=searchEn(list,ad.wEn);
if (k!=-1)
{
cout<<"Введите слово на русском языке \\ ";
cout<<"Write your word RUS"<<endl;
cin >> ad.wRus;
if (ad.wRus[0]>'я' || ad.wRus[0]<'а' )
{
cout<<"Ошибка ввода";
return;
}
OemToCharA(ad.wRus, ad.wRus);
en_rus_in(list,ad.wEn,ad.wRus,k);
cout<<"Выполнено! \\ Complete!"<<endl;
}
}
void delet(listD &list)
{
char *x;
int y, k;
h=list.first;
x=new char[31];
cout<<"Вы выбрали функцию удалить запись \\ You have chosen \"delete record\""<<endl;
cout<<"Введите слово или укажите номер записи \\ Write your word or number of record "<<endl;
cin >> x;
OemToCharA(x,x);
y=chk_lang(x);
if (y==-1)
{
k=atoi(x);
while(h->n!=k && h->n <list.last->n)
h=h->next;
}
else
if (searchEn(list,x,false)!=-1)
if (searchRus(list,x,false)!=-1)
{cout<<"Слово не найдено в словаре, проверьте правильность ввода"<<endl;
return;
}
en_rus_del(list,h);
}
int searchEn(listD list, char* x, bool f) //Бинарный поиск f: поиск по русским-0, по английским-1
//Момент когда начало работать упустил, теперь трогать страшно :D
{
size_t first = list.first->n;
size_t last = list.last->n;
size_t mid;
en_rus *b;
if (list.first == list.last)
{
return 0;
}
else if (strcmp(list.first->wEn, x)>0)
{
return 0;
}
else if (strcmp(list.last->wEn, x)<0)
{
return ((list.last->n)+1);
}
while (first < last)
{
mid = first + (last - first) / 2;
b=list.first;
for(size_t i=1; i<mid;i++)
b=b->next;
if (strcmp(b->wEn, x)>=0 )
{
last = mid;
}
else
{
first = mid + 1;
}
}
b=list.first;
for(size_t i=1; i<last;i++)
b=b->next;
if ( strcmp(b->wEn, x)==0)
{
if (f)
{
cout<<"Слово найдено в словаре, перевод: \\ Word have been searched: "<<endl;
cout<<b->wRus<<endl;
}
h=b;
return -1;
} else
{
return last;
}
}
int searchRus(listD list, char* x, bool f)
{
while (list.first != NULL)
{
if (strcmp(list.first->wRus,x)==0) break;
list.first=list.first->next;
}
if (list.first != NULL)
{
if (f)
{
cout<<"Слово найдено в словаре, перевод: \\ Word have been searched: "<<endl;
cout<< list.first->wEn<< endl;
}
h=list.first;
return -1;
}
else return 0;
}
void out(listD dict)
{
ofstream onFile; // Входной файловый поток
// Открыть файл source и связать его с потоком inFile:
onFile.open("Dictionary.txt", ios::trunc);
if (!onFile) // Проверить правильность открытия файла
{
cerr << "\nОшибка при открытии файла словаря, проверьте наличие словаря в корне";
exit(1); // Завершение программы
}
while (dict.first != NULL)
{
onFile<<dict.first->n<<"."<<dict.first->wEn<<"."<<dict.first->wRus<<".\n";
dict.first = dict.first->next;
}
onFile.close();
}
void translate(listD list)
{
cout<<"Вы выбрали функцию перевести слово \\ You have chosen \"translate word\""<<endl;
cout<<"Введите слово (Анг. или Рус.) \\ Write your word EN or Rus"<<endl;
char x[31];
cin>>x;
OemToCharA(x,x);
if (chk_lang(x)==1) if (searchEn(list, x)!=-1) cout<<"Слова нет в словаре! \\ Dictionare do not have word!"<<endl;
if (chk_lang(x)==0) if (searchRus(list, x)!=-1) cout<<"Слова нет в словаре! \\ Dictionare do not have word!"<<endl;
if (chk_lang(x)==-1) cout<<"Цифры в словаре не хранятся \\ Numbers in the dictionary aren't present"<<endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment