Модераторы: bsa
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Стек - Класс в классе, чтение и удаление из стека, Поковыряйтесь пожулуйста. 
V
    Опции темы
Killer_13
Дата 31.10.2010, 19:56 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 740
Регистрация: 12.1.2008
Где: Germany

Репутация: 1
Всего: 1



Значит задание такое, занести элементы из файла в стек, потом прочитать и удалить.
Вот исходник.
Не могу понять, почему не работает
FifoClass& FifoClass::operator >>(string& str);
FifoClass::operator string();
FifoClass::~FifoClass();


main
Код

/**************************************************************************
  FifoClassTest_1.h

  Testen der Container-Klasse mit Fifo-Eigenschaften

  Dr. B. Lang, FH OS
  12.04.2001: Erste Version
  24.03.2003: Ueberarbeitung fuer OOP-Praktikum SS2003
  19.03.2004: Angepasst an GNU 3.xx Compiler
  23.03.2005: Ueberarbeitung fuer OOP-Praktikum SS2005
  31.03.2006: Nun werden Referenzen von FifoClass gefangen

  To Do:
  - nichts bekannt
/*************************************************************************/
#include<iostream>
using namespace std;
#include "FifoClass.h"

//
// Testprogramm: Textdatei bitte als Argument ьbergeben
//
int main(int argc, char *argv[]) {

  //
  // Normaler Betrieb
  //
  cout << "*** Zunaechst wird der normale Betrieb der Fifo-Klasse abgetestet ***" << endl;
  try {
    cout << "> Fifo aus Textdatei fuellen" << endl;
    FifoClass s( (argc>1) ? argv[1] : "test.txt" ); // Fifo einrichten und aus Textdatei fьllen
    cout << "> Fifo ausgeben" << endl;
    while (s>0) {                           // Elemente ausgeben
      cout << static_cast<string>(s) << endl;
    }
    cout << "> Fifo mittels Ein- und Ausgabeoperator fuellen" << endl;
    s << "One"; s << "Two"; s << "Three";
    cout << "> Fifo ausgeben" << endl;
    string help;
    s >> help; cout << help << endl;
    s >> help; cout << help << endl;
    s >> help; cout << help << endl;
  } catch (FifoClass& f) {
    cout << "> Failure: Fifo Objekt sollte hier keine Ausnahme werfen:" << endl;
    cout << " >>> " << f.Error() << endl;
    return 3;
  } catch (...) {
    cout << "> Failure: Unbekannte Ausnahme" << endl;
    return 3;
  }

  //
  // Fifo Unterlauf testen
  //
  cout << "*** Es werden nun Fifo-Unterlaeufe passieren ***" << endl;
  { FifoClass s; // Leeres Fifo einrichten
    try {
      cout << static_cast<string>(s) << endl;
    } catch (FifoClass& f) {
      cout << "> Erwartete Ausnahme wegen Fifo-Unterlauf:" << endl;
      cout << " >>>> " << f.Error() << endl;
    } catch (...) {
      cout << "> Failure: Unbekannte Ausnahme" << endl;
      return 3;
    }
    try {
      string help;
      cout << "> Fifo mittels Ein- und Ausgabeoperator fuellen" << endl;
      s << "Eins"; s << "Zwei"; s << "Drei";
      cout << "> Fifo ausgeben und Unterlauf herbeifuehren" << endl;
      s >> help; cout << help << endl;
      s >> help; cout << help << endl;
      s >> help; cout << help << endl;
      s >> help; cout << help << endl; // Hier muss ein Unterlauf passieren
    } catch (FifoClass& f) {
      cout << "> Erwartete Ausnahme wegen Fifo-Unterlauf:" << endl;
      cout << " >>>>> " << f.Error() << endl;
    } catch (...) {
      cout << "> Failure: Unbekannte Ausnahme" << endl;
      return 3;
    }
  }

  //
  // Test auf Fehler beim Datei-oeffnen
  //
  cout << "*** Es wird nun eine Ausnahme wegen nicht existierender Datei passieren ***" << endl;
  try {
    FifoClass s( "DieDateiGibtsNicht" ); // Fifo einrichten und aus Datei fьllen
  } catch (FifoClass& f) {
    cout << "> Erwartete Ausnahme wegen nicht existierender Datei:" << endl;
    cout << " >>> " << f.Error() << endl;
  } catch (...) {
    cout << "> Failure: Unbekannte Ausnahme" << endl;
    return 3;
  }
  return 0;
}


FifoClass.h
Код

using namespace std;

class FifoClass {
private:

    class Stack {
    public:
        string line;
        Stack *next;
        Stack(string str);
        ~Stack();
    };

    unsigned int counter;
    Stack *root;
    char* err;

public:
    FifoClass();
    FifoClass(const char*);
    ~FifoClass();

    FifoClass & operator<<(const string&);
    FifoClass & operator>>(string&);
    operator string();
    operator int() const;
    const char* Error() const;
    FifoClass& push(const string&);
    FifoClass& pop(string&);
    
};


FifoClass.cpp
Код

#include<iostream>
#include <fstream>
#include "FifoClass.h"

using namespace std;

//-----------------------------------------------------------------------------

FifoClass::FifoClass() {
    root = NULL;
    counter = 0;
}

//-----------------------------------------------------------------------------

FifoClass::FifoClass(const char* datName) {
    root = NULL;
    counter = 0;
    string row;
    ifstream aus(datName);

    if (!aus.is_open()) {
        cout << "Fehler" << endl;
        throw *this;
    }

    while (!aus.eof()) {
        getline(aus, row, '\n');
        *this << row;
    }
}

//-----------------------------------------------------------------------------

FifoClass& FifoClass::operator <<(const string& str) {

    return push(str);
}

//-----------------------------------------------------------------------------

FifoClass& FifoClass::push(const string& val) {

    Stack *element, *temp;

    try {
        element = new Stack(val);
        counter++;
    } catch (bad_alloc) {
        err = "Kein Speicher vorhanden";
        throw *this;
    }
    if (NULL == root) {
        root = element;
    } else {
        temp = root;
        while (NULL != temp->next)
            temp = temp->next;
        temp->next = element;
        //cout << temp->line << endl;
    }

    return *this;
}

//-----------------------------------------------------------------------------

FifoClass& FifoClass::operator >>(string& str) {

    Stack *temp;

    if (counter == 0) {
        err = "Stack underfloww";
        throw *this;
    }
    str = root->line;

    temp = root;
    root = root->next;
    delete temp;
    counter--;

    return *this;
}

//-----------------------------------------------------------------------------

FifoClass::operator string() {

    string tempStr;
    Stack *temp;

    if (counter == 0) {
        err = "Stack underflow";
        throw *this;
    }
    tempStr = root->line;

    temp = root->next;
    delete root;
    root = temp;
    counter--;

    return tempStr;
}

//-----------------------------------------------------------------------------

FifoClass::operator int () const {
    return counter;
}

//-----------------------------------------------------------------------------

FifoClass::~FifoClass() {

    Stack *current = NULL,
          *to_del = root;
    while (to_del != NULL) {
        current = current->next;
        cout << "Del El= " << to_del->line << endl;
        delete to_del;
        to_del = current;
    }
    root = NULL;

}

//-----------------------------------------------------------------------------

FifoClass::Stack::~Stack() {

}

//-----------------------------------------------------------------------------

FifoClass::Stack::Stack(string str) {
    line = str;
    next = NULL;
}

//-----------------------------------------------------------------------------

const char* FifoClass::Error() const{
    return err;
}




БОЛЬШОЕ СПАСИБО, ЕСЛИ У КОГО НАЙДЕТСЯ МИНУТКА ПОКОВЫРЯТЬСЯ В КОДЕ! smile

PM MAIL   Вверх
rudvil
Дата 31.10.2010, 22:57 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 155
Регистрация: 20.11.2009
Где: Latvia/Riga

Репутация: 1
Всего: 3



Так не проще?

main.cpp такой-же

FifoClass.h
Код
#include<iostream>
#include <fstream>
#include <stack>

using namespace std;

class FifoClass {
private:

  stack<string> stack_;
  string err;
public:
  FifoClass();
  FifoClass(string);
  ~FifoClass();
  void operator<<(const string&);
  void operator>>(string&);
  operator string();
  operator int() const;
  string Error() const;
  void push(const string&);

};

FifoClass.cpp
Код
FifoClass::FifoClass() { }
//-----------------------------------------------------------------------------

FifoClass::FifoClass(string datName) {
  string row;
  ifstream aus(datName.c_str());
  if (!aus.is_open()) {
    cout << "Fehler" << endl;
    throw *this;
  }
  while (!aus.eof()) {
    getline(aus, row, '\n');
    *this << row;
  }
}
//-----------------------------------------------------------------------------

void FifoClass::operator <<(const string& str) {
  return this->stack_.push(str);
}
//-----------------------------------------------------------------------------

void FifoClass::push(const string& val) {
  this->stack_.push(val);
}
//-----------------------------------------------------------------------------

void FifoClass::operator >>(string& str) {
  str = this->stack_.top();
  this->stack_.pop();
}
//-----------------------------------------------------------------------------

FifoClass::operator string() {
  string tempStr = this->stack_.top();
  this->stack_.pop();
  return tempStr;
}
//-----------------------------------------------------------------------------

FifoClass::operator int () const {
  return this->stack_.size();
}
//-----------------------------------------------------------------------------

FifoClass::~FifoClass() { }
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------

string FifoClass::Error() const {
  return err;
}

Цитата(test.txt)
qwerty
hello
world
aaa
bbb
ccc

Цитата(output)
*** Zunaechst wird der normale Betrieb der Fifo-Klasse abgetestet ***
> Fifo aus Textdatei fuellen
> Fifo ausgeben
ccc
bbb
aaa
world
hello
qwerty
> Fifo mittels Ein- und Ausgabeoperator fuellen
> Fifo ausgeben
Three
Two
One
*** Es werden nun Fifo-Unterlaeufe passieren ***

Даже если нужно писать класс стека ручками то переделать будет легко.

Это сообщение отредактировал(а) rudvil - 31.10.2010, 22:59
--------------------
xor
PM MAIL Skype   Вверх
Killer_13
Дата 31.10.2010, 23:02 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 740
Регистрация: 12.1.2008
Где: Germany

Репутация: 1
Всего: 1



rudvil Пасиб, но такое задание. smile 
Я уже разобрался с тем. Там нету проблемы, я неправильно тестировал. :(:(:(
PM MAIL   Вверх
xvr
Дата 1.11.2010, 11:45 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Комодератор
Сообщений: 7046
Регистрация: 28.8.2007
Где: Дублин, Ирландия

Репутация: 35
Всего: 223



Цитата(Killer_13 @  31.10.2010,  23:02 Найти цитируемый пост)
Там нету проблемы
Есть там проблема - вы сделали не стек, а очередь  smile 

PM MAIL   Вверх
Killer_13
Дата 1.11.2010, 11:49 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 740
Регистрация: 12.1.2008
Где: Germany

Репутация: 1
Всего: 1



Бррр, как это? А в чем ну я понимаю различие между стеком и очередью, но не понимаю, почему вы говорите, что эт очередь...
Обясните пож.
PM MAIL   Вверх
xvr
Дата 2.11.2010, 12:03 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Комодератор
Сообщений: 7046
Регистрация: 28.8.2007
Где: Дублин, Ирландия

Репутация: 35
Всего: 223



Цитата(Killer_13 @ 1.11.2010,  11:49)
А в чем ну я понимаю различие между стеком и очередью, но не понимаю, почему вы говорите, что эт очередь...

Потому что ваш push добавляет элементы в хвост списка (см. цикл в строках 57-58 в fifoclass.cpp), а читает из головы списка (см. чтение в строках 78-80 там же). Т.е. первый записанный элемент встанет в голову списка и там и останется, т.е. будет так же прочтен первым, т.е. у вас FIFO (очередь), а нужен LIFO (стек)

PM MAIL   Вверх
Killer_13
Дата 2.11.2010, 13:03 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 740
Регистрация: 12.1.2008
Где: Germany

Репутация: 1
Всего: 1



Пасиб, за поправку, тоисть нужно чуток подправить в этих строчках и все пойдет как нужно.... smile
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "C/C++: Для новичков"
JackYF
bsa

Запрещается!

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Вопросы по реализации алгоритмов рассматриваются здесь


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, JackYF, bsa.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Для новичков | Следующая тема »


 




[ Время генерации скрипта: 0.0709 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.