Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Visual C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 30.09.2014, 18:18   #21
TLandertinger
Пользователь
 
Регистрация: 09.05.2013
Сообщений: 29
По умолчанию

Возникла очередная непонятка.
Код:
#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;//номер ребенка
}; 

// Сам стек
T_family *stack;
// Его вершина и максимум
int top=0,smax;

// Функция помещения в стек
bool push(){
 //Если не превышает пределы стека то норм, иначе вернуть false
 if (top==smax) return false;
 // Просим ввести данные
    int count;	
	T_family a; 
	char c;
	cout << endl << " Enter data of person\n ";
	cout << " fio of father\n";
	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 >> stack[top++].ch[k].d_birth_child.year;
		cin.get(c);
		}
 return true;
}

// Извлекаем из стека
bool pop(){
 //Если конечно есть что извлекать
 if (top<0) return false;
 //Передвигаем указатель с вершины на один вниз
 // показывая данные
 cout   <<"Father: "<<stack[top].fio_father<<'\t'<<stack[top].d_birth_father.day<<'\n'
		<<"Mother: "<<stack[top].fio_mother<<'\t'<<stack[top].d_birth_mother.day<<'\n' 
		<<"Children: "<<stack[top].ch[0].name_of_child<<'\t'<<stack[top].ch[0].d_birth_child.day<<'\n'
                      <<stack[top].ch[1].name_of_child<<'\t'<<stack[top].ch[1].d_birth_child.day<<'\n'
				      <<stack[top].ch[2].name_of_child<<'\t'<<stack[top].ch[2].d_birth_child.day<<'\n'
			          <<stack[top].ch[3].name_of_child<<'\t'<<stack[top].ch[3].d_birth_child.day<<'\n'
                      <<stack[top].ch[4].name_of_child<<'\t'<<stack[top].ch[4].d_birth_child.day<<'\n';

top--;
 return true;
}

void search()
{
  int k_min = 0;
    if(strcmp(stack[top].fio_father, "Ivanov I.I.") == 0 )
    {
      for (int k = 0; k < stack[top].k; k++){
					if (stack[top].ch[k].d_birth_child.year > stack[top].ch[k_min].d_birth_child.year) {
						k_min=k;
					}
					else if (stack[top].ch[k].d_birth_child.year == stack[top].ch[k_min].d_birth_child.year)
					{
						if (stack[top].ch[k].d_birth_child.month > stack[top].ch[k_min].d_birth_child.month) {
							k_min=k;
						}
						else if (stack[top].ch[k].d_birth_child.month == stack[top].ch[k_min].d_birth_child.month)
							if (stack[top].ch[k].d_birth_child.day > stack[top].ch[k_min].d_birth_child.day) {
								k_min=k;
							}
					}		
							break;
    }
	  printf("\n\n!  %10s  ! %2d.%2d.%4d !\n", stack[top].ch[k_min].name_of_child, stack[top].ch[k_min].d_birth_child.day, stack[top].ch[k_min].d_birth_child.month, stack[top].ch[k_min].d_birth_child.year);
  }
}

int main()
{
    //Спрашиваем размер стека
    cout<<"Stack count items please: ";
    cin>>smax;
    stack=new T_family[smax];
    //Забиваем в него данные
    int i;
    for(i=0;i<smax;i++) if(!push()) {cout<<"Problems pushing"<<'\n';break;}
    // Извлекаем из него данные
    for(i=0;i<smax;i++) if(!pop()) {cout<<"Problems popping"<<'\n';break;}
    //Освобождаем стек
    delete[] stack;
    cin.get();
	_getch();
    return 0;
}
Ввод ФИО отца почему-то игнорирует.
P.S. Добавлен поиск младшего ребенка у Иванова И.И. (хотя сомневаюсь, что эта часть кода написана правильно -- она скопирована с предыдущих лаб) Функция извлечения, как требует задание, не нужна(просто забыл указать условия)
Изображения
Тип файла: jpg Das Stack 3.jpg (35.2 Кб, 27 просмотров)

Последний раз редактировалось TLandertinger; 30.09.2014 в 18:28.
TLandertinger вне форума Ответить с цитированием
Старый 30.09.2014, 21:43   #22
Stilet
Белик Виталий :)
Старожил
 
Аватар для Stilet
 
Регистрация: 23.07.2007
Сообщений: 57,097
По умолчанию

Цитата:
cin.getline
А почему не cin<< ?
Тут уже обсуждали много раз особенность cin.getline которая не подхватывает нажатие энтера. Недавно буквально была тема, где спецы по Си наши рекомендовали либо все строки в string хранить либо после getline() вызывать cin.ignore();
I'm learning to live...
Stilet вне форума Ответить с цитированием
Старый 01.10.2014, 09:03   #23
TLandertinger
Пользователь
 
Регистрация: 09.05.2013
Сообщений: 29
По умолчанию

После ввода ФИО отца происходит зацикливание.
Вот код
Код:
#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;//номер ребенка
}; 

int top=0,smax;
class date_of_birth
{
// Сам стек
private:
	T_family *stack;
// Его вершина и максимум
public:
// Функция помещения в стек
bool push(){
 //Если не превышает пределы стека то норм, иначе вернуть false
 if (top==smax) return false;
 // Просим ввести данные
    int count;	
	T_family a; 
	char c;
	cout << endl << " Enter data of person\n ";
	cout << " fio of father ";
	cin >> a.fio_father;
	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 >> a.fio_mother;
	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 >> a.ch[k].name_of_child;
		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 >> stack[top++].ch[k].d_birth_child.year;
		cin.get(c);
		}
 return true;
}

// Извлекаем из стека
void print(){
 //Передвигаем указатель с вершины на один вниз
 // показывая данные
cout<<"Father: "<<stack[top].fio_father<<'\t'<<stack[top].d_birth_father.day<<'\n';
cout<<"Mother: "<<stack[top].fio_mother<<'\t'<<stack[top].d_birth_mother.day<<'\n';
		for (int k = 0; k < stack[top].k; k++)
		{
		cout<<"Children: "<<stack[top].ch[k].name_of_child<<'\t'<<stack[top].ch[k].d_birth_child.day<<'\n';
		}
top--;
}

void search()
{
  int k_min = 0;
    if(strcmp(stack[top].fio_father, "Ivanov I.I.") == 0 )
    {
      for (int k = 0; k < stack[top].k; k++){
					if (stack[top].ch[k].d_birth_child.year > stack[top].ch[k_min].d_birth_child.year) {
						k_min=k;
					}
					else if (stack[top].ch[k].d_birth_child.year == stack[top].ch[k_min].d_birth_child.year)
					{
						if (stack[top].ch[k].d_birth_child.month > stack[top].ch[k_min].d_birth_child.month) {
							k_min=k;
						}
						else if (stack[top].ch[k].d_birth_child.month == stack[top].ch[k_min].d_birth_child.month)
							if (stack[top].ch[k].d_birth_child.day > stack[top].ch[k_min].d_birth_child.day) {
								k_min=k;
							}
					}		
							break;
    }
	  printf("\n\n!  %10s  ! %2d.%2d.%4d !\n", stack[top].ch[k_min].name_of_child, stack[top].ch[k_min].d_birth_child.day, stack[top].ch[k_min].d_birth_child.month, stack[top].ch[k_min].d_birth_child.year);
  }
}
};

int main()
{
	date_of_birth d;
    //Спрашиваем размер стека
    cout<<"Stack count items please: ";
    cin>>smax;
    T_family *stack=new T_family[smax];
    //Забиваем в него данные
    int i;
    for(i=0;i<smax;i++) if(!d.push()) {cout<<"Problems pushing"<<'\n';break;}
	cout << "\nlist of structs\n!      name           !  date of birth !\n";
	for(i=0;i<smax;i++)
	{
		d.push();
	}
	for(i=0;i<smax;i++)
	{
		d.print();
	}
	d.search();
    //Освобождаем стек
    delete[] stack;
    cin.get();
	_getch();
    return 0;
}
Может, что-то не так с кодом?
P.S. После закрытия консоля пишет: STATUS_STACK_BUFFER_OVERRUN encountered

Последний раз редактировалось TLandertinger; 01.10.2014 в 09:09.
TLandertinger вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Стек Igor95 Общие вопросы C/C++ 19 17.01.2013 04:31
Стек на С++ Electroflower Общие вопросы C/C++ 37 05.01.2012 14:20
Стек Darknes Общие вопросы C/C++ 2 11.04.2011 23:30
Стек [ICQ] Помощь студентам 5 02.05.2010 13:44
стек в с++ Aleksa_ks Помощь студентам 0 02.05.2010 12:12