/* Еще вопрос: почему когда добавляю из первой базы во вторую элементы, и последним элементом добавляю во 2 базу первый из базы 1, а затем хочу обратно из базы 2 засунуть в базу 1 они тупо пропадают при добавлении в первую базу. Как поправить? */ #include <string.h> #include <iostream> #include <conio.h> using namespace std; class List//Базовый класс { protected: struct Element { char name[55]; int n_bus; int n_mar; Element *next; } *start, *pbeg; public: List(); List(const List&); List &operator=(const List&); virtual ~List(); void show_list(); void filee(); }; class NaMarshrut: public List//Производный класс от класса List { public: Element* starts; Element* pbegs; NaMarshrut(); ~NaMarshrut(); void show_NaMarshrut(); int dell(int emp_nomer); int add(int emp_nomer); }; List::List()//Конструктор базвого класса по умолчанию { pbeg = NULL; start = NULL; } List::~List()//Деструктор базового класса { while(start) { Element* temp = start; start = start->next; delete temp; temp = NULL; } } void List::show_list()//Вывод результата базового класса { system("cls"); cout<<"*****СПИСОК АВТОБУСОВ В ГАРАЖЕ*****"<<"\n\n"; if(start) { Element* t = start; while(t) { cout<<"Номер автобуса: "<< t->n_bus <<"\n"; cout<<"Имя водителя: "<< t->name <<"\n"; cout<<"Номер маршрута: "<< t->n_mar <<"\n\n"; t = t->next; } } else { // cout<<"*****СПИСОК АВТОБУСОВ В ГАРАЖЕ*****"<<"\n\n"; cout<<"В гараже нет никого!"<<"\n\n"; } } void List::filee()//Работа с файлом { FILE* in; const int SIZE = 55; char fn[SIZE],c; int qr=0; while(true) { cout <<"Введите имя файла: "; cin.getline(fn,SIZE); in=fopen(fn,"r"); if (!in) { cout << "Error: Нет такого файла.\n"; continue; } while((c=fgetc(in)) != EOF) { qr++; } if(qr==0) { cout << "Error: Файл пуст.\n"; rewind(in); continue; } else { rewind(in); break; } } while(true) { if(start) { Element *q = new Element; fscanf(in,"%i",&q->n_bus); fscanf(in,"%s",&q->name); fscanf(in,"%i",&q->n_mar); if(q->n_bus<-1 || q->n_mar<-1) { system("cls"); cout<<"Error: Некорректные данные в файле"; _getch(); exit(EXIT_SUCCESS); } q->next = pbeg->next; pbeg->next = q; pbeg = q; } else { pbeg = new Element; fscanf(in,"%i",&pbeg->n_bus); fscanf(in,"%s",&pbeg->name); fscanf(in,"%i",&pbeg->n_mar); if(pbeg->n_bus<-1 || pbeg->n_mar<-1) { system("cls"); cout<<"Error: Некорректные данные в файле"; _getch(); exit(EXIT_SUCCESS); } pbeg->next = NULL; start = pbeg; } if(feof(in)) break; } fclose(in); } NaMarshrut::NaMarshrut():List()//Конструктор по умолчанию { starts = NULL; pbegs = NULL; } NaMarshrut::~NaMarshrut() { pbegs = starts; while(pbegs) { Element* temps = pbegs; pbegs = pbegs->next; delete temps; temps = NULL; } } void NaMarshrut::show_NaMarshrut()//Вывод на экран { show_list(); if(starts) { cout<<"*****СПИСОК АВТОБУСОВ НА МАРШРУТЕ*****"<<"\n\n"; Element* t = starts; while(t) { cout<<"Номер автобуса: "<< t->n_bus <<"\n"; cout<<"Имя водителя: "<< t->name <<"\n"; cout<<"Номер маршрута: "<< t->n_mar <<"\n\n"; t = t->next; } } else { // cout<<"*****СПИСОК АВТОБУСОВ НА МАРШРУТЕ*****"<<"\n\n"; cout<<"На маршруте нет никого!"<<"\n\n"; } } int NaMarshrut::dell(int emp_nomer)//На маршрут { Element* q = start; pbeg = start; Element* temps = new Element; if(start) { bool flag; Element* flags = start; while(flags) { if(flags->n_bus == emp_nomer)//Сравнение введнного значения с первым элементом списка { flag = true; break; } else flag = false; flags = flags->next; } if(flag)//Если мы нашли совпадение номеров,то.... { while(q)//Пока не перебрали весь список(!=NULL) { if(emp_nomer == start->n_bus)//Если номер равен 1му { Element* tem = start; start = start->next; strcpy(temps->name,tem->name); temps->n_bus = tem->n_bus; temps->n_mar = tem->n_mar; delete tem; break; } else { Element* p = q->next;//Берем элемент +1 if(p) { if(p->n_bus == emp_nomer) { q->next = p->next; strcpy(temps->name,p->name); temps->n_bus = p->n_bus; temps->n_mar = p->n_mar; delete p; break; } } else//Если следующий NULL ,тоест последниий был { strcpy(temps->name,p->name); temps->n_bus = p->n_bus; temps->n_mar = p->n_mar; delete q; break; } } q = q->next; } } else { system("cls"); cout<<"Такого автобуса нет в ГАРАЖЕ\n\n"; _getch(); return 0; } } else { cout<<"Гараж пуст!"<<endl; _getch(); return 0; } if(starts) { Element* mar = temps; mar->next = pbegs->next; pbegs->next = mar; pbegs = mar; return 0; } else { pbegs = temps; pbegs->next = NULL; starts = pbegs; return 0; } } int NaMarshrut::add(int emp_nomer)//В гараж { Element* q = starts;//Контейнер для перебора элементов для сравнения с введнным номером Element* temps = new Element;//Запись подходящего элемента в контейнер pbegs = starts; if(starts) { bool flag; Element* flags = starts; while(flags) { if(flags->n_bus == emp_nomer) { flag = true; break; } else flag = false; flags = flags->next; } if(flag) { while(q) { if(emp_nomer == starts->n_bus) { Element* tem = starts;//Кладем 1 в тем starts = starts->next;//Стартовый становится следующим ++ strcpy(temps->name,tem->name); temps->n_bus = tem->n_bus; temps->n_mar = tem->n_mar; delete tem; break; } else { Element* p = q->next;//Кладем второй элемент не стартовый if(p) { if(p->n_bus == emp_nomer) { q->next = p->next; strcpy(temps->name,p->name); temps->n_bus = p->n_bus; temps->n_mar = p->n_mar; delete p; break; } //--------------Кидает в это условие когда с проблема с первым элементом,потом начинается пропадание элементов обратно в базу1--------------------// else { cout<<"Такого автобуса нет на МАРШРУТЕ\n\n"; _getch(); return 0; } //--------------------------------------------------------------------------------------------// } else { strcpy(temps->name,p->name); temps->n_bus = p->n_bus; temps->n_mar = p->n_mar; delete q; break; } } q = q->next; } } else { system("cls"); cout<<"Такого автобуса нет на МАРШРУТЕ\n\n"; _getch(); return 0; } } else { cout<<"Маршрут пуст!\n\n"; _getch(); return 0; } if(start) { Element* mar = temps; mar->next = pbeg->next; pbeg->next = mar; pbeg = mar; return 0; } else { pbeg = temps; pbeg->next = NULL; start = pbeg; return 0; } } int main() { setlocale(LC_ALL,"Russian"); NaMarshrut war; war.filee(); int emp_nomer; while(true) { int x; war.show_NaMarshrut(); cout<<"1) На маршрут."<<endl; cout<<"2) В гараж."<<endl; cout<<"3) Выход."<<endl; if((!fflush(stdin) && cout<<"\n\nВВОД: " && !(cin >> x))||(x<1) ||(x>3)) { cin.clear(); system("cls"); continue; } switch(x) { case 1 : while(!fflush(stdin) && cout<<"Введите № автобуса выезжающего на маршрут: " && !(cin >> emp_nomer)) { cin.clear(); } war.dell(emp_nomer); continue; case 2 : while(!fflush(stdin) && cout<<"Введите № автобуса приехавшего в гараж: " && !(cin >> emp_nomer)) { cin.clear(); } war.add(emp_nomer); continue; case 3: system("cls"); return 0; } } }
- Is there anyone alive? - wapdimon72ru
- eightPeople open a question, leaf through this roll, close a question. - teanYCH
- Fucked up! David Blaine! Not! - nolka
- one@ wapdimon72ru, pun) I really thought that "is there anyone alive, reading this comment, after the given code array" ... - Salivan 6:51
2 answers
Extremely clumsy code:
- tmp = 0, fbeg = 0, etc. must be replaced by tmp = NULL, fbeg = NULL, etc.
- exit (0) replace with exit (EXIT_SUCCES). In short - get rid of the "magic numbers"
- In the List :: show_list, in the case of start == false, the phrase " ** BUS LIST IN THE GARAGE **" << "\ n \ n" is displayed twice
- The List :: filee () function uses char, although it would be more logical to use wchar_t, otherwise you will have problems with Russian letters in the file paths.
- char fn [55] - again "magic numbers"
- List :: filee - mixes C and C ++ style input. Use some one.
- List copy constructor - you lose copied elements p-> next = 0
- List :: operator = - flows
- What for two while in NaMarshrut :: del, put it in one - don't look for the same element twice
- Same NaMarshrut :: add.
- The NaMarshrut copy constructor is due to the string src_p1 = src_p1-> next; at the beginning of the code does not copy the first element.
This is something that can be found just by running around. In the meantime, not that digging, just read this code reluctance.
Part 2.
4) It did not work out apparently because of the strcpy string (temps-> name, p-> name). Other standard functions work with wide strings with the prefix wcs (usually). You need wcscpy (temps-> name, p-> name), objects instead of cin and cout - wcin and wcout.
7) It is necessary to store the previous element and assign the current element to it. You probably had something similar, since there is a line // prev-> next = p;
8) The new operator allocates memory for some object. If you do not delete the object after this, it does not disappear anywhere - it continues to hang in the memory. If there is no pointer to this object, they say that "memory is flowing." However, I looked carefully at the code - I still take the words back, you delete them. Somewhere behind the eye, something is hooked, apparently ...
9) The easiest:
Element* bus = NULL; Element* prev_bus = null; Element* flags = starts; while((bus == NULL) && (flags != NULL)) { if(flags->n_bus == nomer) { bus = flags; if (prev_bus == NULL) { //действия если элемент первый } else { //действия если элемент не первый, у вас к тому же есть //ссылка на предыдущий элемент prev_bus } } prev_bus = flags; flags = flags->next; } if(bus != NULL) { //какие-то действия }
If I understand correctly and you fixed the NaMarshrut copy constructor, then your error is in clause 7.
- 1. Made 2. Also replaced 3. Removed unnecessary 4. Did not do
wchar_t
, did not work 5.char fn[55]
- again "magic numbers" The length under the file name 55 is 6. This is skipped 7. And how then to replace? 8. What does flowing mean? How to fix? 9. I think how to do it in one 10. The same 11. I did what I copy. I know the code is crooked. I am learning only for the time being, everything will be fine with time. Thanks for the advice. And yet the answer to the main question was not given. I'm talking about the problem with the first element. - wapdimon72ru - 5) const int SIZE = 55; char fn [SIZE]; If you change the length under the file name - you will have to change a lot less code. The rest will answer in the evening. - Mirdin
- Thanks for responding, I accept the advice, and continue to use it, but now I have all the attention to the problem with the element first, the problem as in the first post. - wapdimon72ru
- Interestingly, why was the garden itself, to write its own implementation of the list, and not to use STL. Corrected the answer above. - Mirdin
- starts = starts-> next; // the starting one becomes the following ++ Here it’s not the starting one that becomes the next, but the next one starting, and accordingly the starting one disappears. For paragraph 9, why did not work? - Mirdin
1)В однонаправленном списке нету ведь указателя на предыдущий элемент,а есть следующий,текущий и стартовый. 2)По п.9 можете под мои перемнные сделать?Ну или взять и скопировать текст чтоб код полный был. А может возмете код с первого поста,вставите свою часть и разместите на pastecode.ru,чтоб не было проблем со вставкой кода,просто уже не получается ваши вещи из последних постов реализовать
- In the unidirectional list there really isn’t, but you can use pointers in your function, and in addition to the pointers stored in the list. What's so complicated? - Mirdin
- In the code can do? - wapdimon72ru
- And what in these functions you add / delete - now you are just juggling with pointers. For example, the add function we found a bus by the condition - what should we do, we did not find - what to do? - Mirdin
- Tell me how to do it? IN CODE - wapdimon72ru
- people help ??) - wapdimon72ru