Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / C++ [игнор отключен] [закрыт для гостей] / Деревья. Необработанное исключение. / 8 сообщений из 8, страница 1 из 1
11.08.2014, 16:46
    #38717458
TLandertinger
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Деревья. Необработанное исключение.
Здравствуйте. У меня возникли проблемы. Вот задание:
Описать массив записей "семья".

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
--------------------------------------------------------------
     Отец      !      Мать    !  Ребенок  !         ! Ребенок
--------------------------------------- -----------
Ф.И.О.!дата !Ф.И.О.!дата ! Имя !дата ! ...... ! Имя !дата
         !рожд.!        !рожд.!      !рожд.!        !       !рожд.
---------------------------------------------------------------
                               !__________________ ________________!
                                              не более 5 детей


Найти и вывести имя младшего ребенка у Иванова И.И. по форме

Код: plaintext
1.
2.
3.
_______________________________
имя ребенка ! дата рождения !
-----------------------------------
Программа выдала необработанное исключение и вдобавок результат вывелся не совсем корректно. Что я сделал неправильно?

Вот мой код:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
// laba 12-1.cpp: главный файл проекта.
#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

struct Date 		
{
	unsigned day; 		
	unsigned month;		
	unsigned year;
};

struct Children
{
	char name_of_child[30];
	Date d_birth_child;
};

struct T_family 
{
	char fio_father[30];
	Date d_birth_father;
	char fio_mother[30];
	Date d_birth_mother;
	Children ch[5];
	int k;
}; 

struct TreeNode
{
	int k;
	T_family family;
	Children ch[5];
	TreeNode *next;
	TreeNode *child;
};

class date_of_birth
{
private:
	TreeNode *head;
public:
date_of_birth()
	{
		head = new TreeNode;
		TreeNode *node1 = new TreeNode;
		node1->k = 1;
		node1->child = NULL;
		node1->next = NULL;
		head->child = node1;
		TreeNode *node2 = new TreeNode;
		node2->k = 2;
		node2->child = NULL;
		node2->next = NULL;
		node1->next = node2;
		TreeNode *node3 = new TreeNode;
		node3->k = 3;
		node3->child = NULL;
		node3->next = NULL;
		node2->next = node3;
		T_family a = {"Ivanov I. I.", 21,5,1965,"Ivanova E.G.",13,2,1967,"Oleg",19,7,1994,"Olga",13,8,1996};
		TreeNode *nodeA = new TreeNode;
		nodeA->family = a;
		nodeA->child = NULL;
		nodeA->next = NULL;
		node1->child = nodeA;
		T_family b = {"Petrov P. P.", 12,4,1962,"Petrova E.O.",8,12,1965,"Pavel",12,4,1988,"Ekaterina",24,8,1992};
		TreeNode *nodeB = new TreeNode;
		nodeB->family = b;
		nodeB->child = NULL;
		nodeB->next = NULL;
		node2->child = nodeB;
}

void add_node(int i)
	{
	int count;		
	T_family a; 
	char c;
	cout << endl << " Enter data of" << i+1 << "person\n ";
	cout << " fio of father ";
	cin.getline (a.fio_father, 30);
	cout << "Enter date of father's birthday: \n";
	cout << " day (1-31) ";
	cin >> a.d_birth_father.day;
	cin.get(c);
	cout << " month (1-12)";
	cin >> a.d_birth_father.month;
	cin.get(c);
	cout << " year ";
	cin >> a.d_birth_father.year;
	cin.get(c);
	cout << " fio of mother ";
	cin.getline (a.fio_mother, 30);
	cout << endl <<"Enter date of mother's birthday: \n";
	cout <<" day (1-31) ";
	cin >> a.d_birth_mother.day;
	cin.get(c);
	cout << " month (1-12)";
	cin >> a.d_birth_mother.month;
	cin.get(c);
	cout << " year ";
	cin >> a.d_birth_mother.year;
	cin.get(c);
	//запросить кол-во детей и запомнить в count
	cout << "Enter count of children" << endl;
	cin >> count;
	cin.get(c);
	if ((count > 5) && (count < 0)) cout << " Fatal error " << endl;
	a.k = count;
	for (int k=0; k < count; k++) {
		cout << endl << " Name of " " " << k+1 << " " " child ";
		cin.getline (a.ch[k].name_of_child, 30);
		cout << endl << "Enter date of" " "<< k+1 << " " "child's birthday: \n";
		cout <<" day (1-31) ";
		cin >> a.ch[k].d_birth_child.day;
		cin.get(c);
		cout << " month (1-12)";
		cin >> a.ch[k].d_birth_child.month;
		cin.get(c);
		cout << " year ";
		cin >> a.ch[k].d_birth_child.year;
		cin.get(c); 
	}

     	TreeNode *node = head->child;
		while(true)
		{
			if(node->k == a.k)
			{
				TreeNode *newNode = new TreeNode;
				newNode->family = a;
				newNode->child = NULL;
				newNode->next = NULL;
				if(node->child == NULL)
					node->child = newNode;
				else 	
				{
					TreeNode *elem = node->child;
					while(elem->next != NULL)
						elem = elem->next;
					elem->next = newNode;
				}
				return;
			}
			if(node->next == NULL)
				break;
			node = node->next;
		}

		TreeNode *newNode = new TreeNode;
		newNode->k = a.k;
		newNode->child = NULL;
		newNode->next = NULL;
		node->next = newNode;
		TreeNode *nodeA = new TreeNode;
		nodeA->family = a;
		nodeA->child = NULL;
		nodeA->next = NULL;
		newNode->child = nodeA;
	}

void print_tree()
	{
		printf("[ \n");
		TreeNode *node = head->child;
		while(node != NULL)
		{
			cout << " --> " << node->k << endl;
			if(node->child != NULL)
			{
				TreeNode *child = node->child;
				while(child != NULL)
				{
				printf("! %10s ! %2d.%2d.%4d !",child->family.fio_father, child->family.d_birth_father.day, child->family.d_birth_father.month, child->family.d_birth_father.year);
				printf("! %10s ! %2d.%2d.%4d !",child->family.fio_mother, child->family.d_birth_mother.day, child->family.d_birth_father.month, child->family.d_birth_father.year);
				for (int k = 0; k < child->family.k ; k++) {
				printf("! %10s ! %2d.%2d.%4d!", child->family.ch[k].name_of_child, child->family.ch[k].d_birth_child.day, child->family.ch[k].d_birth_child.month, child->family.ch[k].d_birth_child.year);
				printf("\n");
														   }
					child = child->next;
				}
			}
			node = node->next;
		}
		printf("]\n");
	}

void find_min()
	{
		int k_min = 0;
		TreeNode *node = head->child;
		TreeNode *young = node->child;
		while(node != NULL)
		{
			if(node->k < young->k && node->child != NULL)
				young = node->child;
			node = node->next;
			k_min = young->k;
		}
	
printf("!  %10s  ! %2d.%2d.%4d !\n", young->family.ch[k_min].name_of_child, young->family.ch[k_min].d_birth_child.day, young->family.ch[k_min].d_birth_child.month, young->family.ch[k_min].d_birth_child.year);
	}
};

int main()
{
	cout << "       Avtor - Shusharin A.V., student gr. ISEbd-11" << endl;
	cout << "       Variant N 1" << endl;
	cout << "       Programma sozdaet massiv structur, zapolnaet ego dannimi i vivodit na ekran etot massiv v vide tablici"  << endl;
	cout << "       Programma opredelaet i vivodit imya mladshego rebenka u Ivanova I.I"  << endl;
	date_of_birth d;
	for(int i = 2; i < 3; i++)
	{ 	
		d.add_node(i);
	};
	cout << "\nlist of structs\n!       father        !       mother        !        child        !\n";
	d.print_tree();
	d.find_min();
	_getch();
    return 0;
}


Ошибка приведена в скриншоте.
...
Рейтинг: 0 / 0
11.08.2014, 16:56
    #38717473
Leonid Kudryavtsev
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Деревья. Необработанное исключение.
TLandertingerЧто я сделал неправильно?

Не прочел главу учебника которая называлась "Отладка приложения" (debug).

После шага "написать" обычно должен идти шаг "отладка, проверка, тестирование"
...
Рейтинг: 0 / 0
11.08.2014, 16:58
    #38717479
mayton
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Деревья. Необработанное исключение.
другая память повреждена
Это капец какой-то! Все технические переводчики рыдают горькими слезами.
Да лучше-б вообще не переводили...

Девять из 10 юзеров побегут в сервисный центр менять планку памяти.
...
Рейтинг: 0 / 0
11.08.2014, 20:50
    #38717651
Dima T
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Деревья. Необработанное исключение.
maytonДевять из 10 юзеров побегут в сервисный центр менять планку памяти.
Оптимистично, думаю все 11, т.к. один из десяти даст проверить прогу товарищу
...
Рейтинг: 0 / 0
12.08.2014, 02:24
    #38717737
SashaMercury
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Деревья. Необработанное исключение.
решил посмотреть на ваш код.
Объясните почему вы так странно спроектировали семью ?

В первом приближении даже так лучше

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
struct Date
{
	char day;
	char month;
	unsigned year;
};

struct Person
{
	char name[100];
	struct Date birth;
};

struct T_family
{
	struct Person f;
	struct Person m;
	struct Person* ch=NULL;//во время работы нужно память выделять, столько сколько нужно
	int k;//зачем ?
};

struct TreeNode
{
	int k;
	T_family family;
	Children ch[5];//зачем вам тут снова дети ?
	TreeNode *next;
	TreeNode *child;
};
...
Рейтинг: 0 / 0
12.08.2014, 02:34
    #38717738
SashaMercury
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Деревья. Необработанное исключение.
В общем, я начал рыть глубже. Мне ваш код совсем не нравится. Вот так я исправил, дальше делайте сами:

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
struct Date
{
	char day;
	char month;
	unsigned year;
};

struct Person
{
	char name[100];
	struct Date birth;
};

struct T_family
{
	struct Person f;
	struct Person m;
	struct Person* ch=NULL;//во время работы нужно память выделять, столько сколько нужно
	int k;//зачем ?
};

struct TreeNode
{
	int k;
	T_family family;
	TreeNode *next;
};

class date_of_birth
{
private:
	TreeNode *head;
public:
	TreeNode* createTN(int k, TreeNode* next)
	{
		TreeNode* n = (TreeNode*)malloc(sizeof(TreeNode));
		n->k = k;
		n->next = next;
	}


	date_of_birth()
	{
		head = new TreeNode;
		TreeNode* n1 = createTN(1, NULL);
		TreeNode* n2 = createTN(2, NULL);
		TreeNode *n3 = createTN(2, NULL);
		n2->next = n3;

		....

	
	}
...
Рейтинг: 0 / 0
12.08.2014, 02:39
    #38717739
SashaMercury
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Деревья. Необработанное исключение.
Ошибка у вас в функции void fnd_min(), на выводе
Код: plaintext
1.
printf("!  %10s  ! %2d.%2d.%4d !\n", young->family.ch[k_min].name_of_child ...



проблема с name_of_child.

Поставьте точку останова и посмотрите.


Хотя нет, ошибка у вас, в совсем плохом проектировании. Исправьте код, я вас убедительно прошу.
...
Рейтинг: 0 / 0
12.08.2014, 13:06
    #38718073
mayton
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Деревья. Необработанное исключение.
Код: plaintext
1.
2.
3.
4.
5.
6.
#include <ctime>

struct Date
{
	time_t date;
};
...
Рейтинг: 0 / 0
Форумы / C++ [игнор отключен] [закрыт для гостей] / Деревья. Необработанное исключение. / 8 сообщений из 8, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]