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

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

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

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

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

Ответ
 
Опции темы Поиск в этой теме
Старый 11.04.2010, 18:57   #1
Дырдин
Пользователь
 
Аватар для Дырдин
 
Регистрация: 26.09.2009
Сообщений: 81
По умолчанию Не читает ВЕСЬ объект из файла

Программа должна записывать/считывать в бинарный файл стек, который я сам же и создаю. Почему считывает только один элемент стека?

Команда записи = "writeB"
Команда чтения = "readB"

Код:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
class list{
public:
	list *head;
	list *tail;
	list *next;
	int raiting;
	char *female;
	list() {head = tail = next = NULL;};
	virtual void add(int raiting, char f[64], int len) = 0;
	virtual void output() = 0;
	inline void erase(char *str);
};

inline void list::erase(char *str)
{
	if(!head){
		cout << str << " is clear!" << endl;
	}
	else{
		list *l;
		l = head;
		head = head->next;
		delete l;
		erase(str);
	}
}

class stack : public list{
public:
	void add(int rating, char f[64], int len);
	void output();
};

void stack::add(int raiting, char f[64], int len)
{
	list *item;
	item = new stack;
	if(!item){
		cout << "Memory error!" << endl;
		exit(1);
	}
	item->raiting = raiting;
	item->female = new char [len];
	for(int i = 0; i < len; i++){
		item->female[i] = f[i];
	}
	item->female[len] = '\0';
	if(head){
		item->next = head;
	}
	head = item;
	if(!tail){
		tail = head;
	}
}

void stack::output()
{	
	if(!head){
		cout << "Stack empty!" << endl;
	}
	else{
		int tmp;
		char *tmp2;
		tmp = head->raiting;
		tmp2 = head->female;
		head = head->next;
		cout << "Student: " << tmp2 << ", rating = " <<  tmp << endl;
	}
}

void in_action(stack &s, char action[10]);
void binary_write(stack s);

int main()
{
	system ("color 74");	
	stack s;
	while(true){
		char action[10];
		cout << "Input action = ";
		cin >> action;
		if(strstr("readB", action)){
			ifstream b_read("binary.stack");
			b_read.read(reinterpret_cast<char*>(&s), sizeof(stack));
			b_read.close();
			cout << "Stack is read from binary!" << endl;
		}
		else{
			in_action(s, action);
		}
	}
}

void in_action(stack &s, char action[10])
{
	if(strstr("add", action)){
		int raiting;
		char female[64];
		cout << "What female of student? = ";
		cin >> female;
		cout << "What raiting of student? = ";
		cin >> raiting;
		int len = strlen(female);
		s.add(raiting, female, len);
	}
	if(strstr("show", action)){
		int amount;
		cout << "How many element to show? = ";
		cin >> amount;
		for(int i = 0; i < amount; i++){
			s.output();
		}
	}
	if(strstr("clear", action)){
		s.erase("Stack");
	}
	if(strstr("writeB", action)){
		binary_write(s);
	}
}


void binary_write(stack s)
{
	ofstream b_write("binary.stack");
	b_write.write(reinterpret_cast<char*>(&s), sizeof(stack));
	b_write.close();
	cout << "The file is written as binary!" << endl;
}
Дырдин вне форума Ответить с цитированием
Старый 12.04.2010, 01:20   #2
l4h
Новичок
Джуниор
 
Регистрация: 11.04.2010
Сообщений: 3
По умолчанию

Смотри, что я бы тебе посоветовал =)
Для начала в немного изменить класс list, добавить в него private и отправить туда переменные, ведь у тебя есть интерфейс для их заполнения-функция add(), тогда зачем они торчат наружу? И описать назначение каждой из функций, это добавит понимания и тебе =)
Как я вижу, загрузка у тебя производится прямо из main, сколько раз она должна пройти по твоему? я вижу только один раз, после чего снова попросит ввести ключевое слово отталкиваясь от которого будет что-то выполнять.

Последний раз редактировалось l4h; 12.04.2010 в 01:31.
l4h вне форума Ответить с цитированием
Старый 13.04.2010, 09:04   #3
Дырдин
Пользователь
 
Аватар для Дырдин
 
Регистрация: 26.09.2009
Сообщений: 81
По умолчанию

Сделал цикл, но всё равно не работает

Код:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
class list{
public:
	list *head;
	list *tail;
	list *next;
	int raiting;
	char *female;
	list() {head = tail = next = NULL;};
	virtual void add(int raiting, char f[64], int len) = 0;
	virtual void output() = 0;
	inline void erase(char *str);
};

inline void list::erase(char *str)
{
	if(!head){
		cout << str << " is clear!" << endl;
	}
	else{
		list *l;
		l = head;
		head = head->next;
		delete l;
		erase(str);
	}
}

class stack : public list{
public:
	void add(int rating, char f[64], int len);
	void output();
};

void stack::add(int raiting, char f[64], int len)
{
	list *item;
	item = new stack;
	if(!item){
		cout << "Memory error!" << endl;
		exit(1);
	}
	item->raiting = raiting;
	item->female = new char [len];
	for(int i = 0; i < len; i++){
		item->female[i] = f[i];
	}
	item->female[len] = '\0';
	if(head){
		item->next = head;
	}
	head = item;
	if(!tail){
		tail = head;
	}
}

void stack::output()
{	
	if(!head){
		cout << "Stack empty!" << endl;
	}
	else{
		int tmp;
		char *tmp2;
		tmp = head->raiting;
		tmp2 = head->female;
		head = head->next;
		cout << "Student: " << tmp2 << ", rating = " <<  tmp << endl;
	}
}

void in_action(stack &s, char action[10]);
inline void binary_write(stack &s);
inline void binary_read(stack &s);

int main()
{
	system ("color 74");	
	stack s;
	while(true){
		char action[10];
		cout << "Input action = ";
		cin >> action;
		in_action(s, action);
	}
}

void in_action(stack &s, char action[10])
{
	if(strstr("add", action)){
		int raiting;
		char female[64];
		cout << "What female of student? = ";
		cin >> female;
		cout << "What raiting of student? = ";
		cin >> raiting;
		int len = strlen(female);
		s.add(raiting, female, len);
	}
	if(strstr("show", action)){
		int amount;
		cout << "How many element to show? = ";
		cin >> amount;
		for(int i = 0; i < amount; i++){
			s.output();
		}
	}
	if(strstr("clear", action)){
		s.erase("Stack");
	}
	if(strstr("wB", action)){
		system("erase binary.stack /Q");
		binary_write(s);
	}
	if(strstr("rB", action)){
		binary_read(s);
	}
	if(strstr("close", action)){
		exit(1);
	}
}


inline void binary_write(stack &s)
{
	ofstream b_write("binary.stack", ios::app);
	if(s.head){
		b_write.write(reinterpret_cast<char*>(&s), sizeof(stack));
		b_write.close();
		s.head = s.head->next;
		binary_write(s);
	}
	else{
		cout << "The file is written as binary!" << endl;
	}
}

//считывание, где и возникают проблемы
inline void binary_read(stack &s)
{
	int count = 0;
	ifstream b_read("binary.stack");
	while(!b_read.eof()){
		list *item;
		item = new stack;
		b_read.read(reinterpret_cast<char*>(&s), sizeof(stack));
		if(s.head){
			item->next = s.head;
		}
			s.head = item;
		if(!s.tail){
			s.tail = s.head;
		}
		delete item;
		count++;
	}
	b_read.close();
	count--;
	cout << "Stack was read from binary! It have " << count << " elements." << endl;
}
Дырдин вне форума Ответить с цитированием
Ответ


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



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Кто что читает Utkin Свободное общение 22 12.01.2010 15:52
Читает вывод из консоли Consol Win Api 10 31.08.2009 08:42
Как в объект Memo вставить текст из файла Antyan-screammer Общие вопросы Delphi 6 09.08.2009 19:33
Можно ли считывать часть большого BMP файла не считывая весь? Miklek Мультимедиа в Delphi 5 17.04.2009 09:20
плеер Divx не читает Xatr Софт 4 26.12.2008 03:00