2012-05-20 1 views
-1

Так что я работаю над этим проектом для школы. У меня все работает. Сначала я построил связанный список, и в коде вы видите, что он берет все хорошо и печатает его. Когда я пытаюсь использовать меню для вставки элементов в список, он работает. Я сделал несколько распечаток, чтобы узнать, что происходит. Когда я печатаю список, только элементы, вмененные в меню, выходят из строя.Может ли кто-нибудь сказать мне, почему мусор печатается из моего связанного списка?

Я просмотрел несколько сообщений, которые указывают на такую ​​же проблему, но я не вижу, где в моем коде может возникнуть проблема.

Можете ли вы, ребята, просмотреть функции и посмотреть, не делаю ли я что-то неправильно. Я, насколько я вижу, все это, похоже, работает, но на выходе полно мусора. Спасибо за помощь вот код для проекта

Word.h

class Word 
{ 

public: 
    void SetEnglish(char *word); 
    char *GetEnglish(); 
    void SetFinnish(char *word); 
    char *GetFinnish(); 
    void SetPrev(Word *word); 
    Word *GetPrev(); 
    void SetNext(Word *word); 
    Word *GetNext(); 

private: 
    char *English; 
    char *Finnish; 
    Word *prev;   //pointer to previous node 
    Word *next;   //pointer to next node 


}; 

class dlist 
{ 
public: 

    Word *front;  //pointer to front of list 
    Word *back;  //pointer to back of list 

dlist() 
{ 
    front=NULL; 
    back=NULL; 
} 

void insertFront(char *Eng, char *Fin);    
int insertBack(char *Eng, char *Fin); 
void insertBefore(char *Eng, char *Fin, Word *nodeB); 
void insertAfter(char *Eng, char *Fin, Word *nodeA); 
void printDListFront(); 

}; 

Word.cpp

#include <iostream> 
#include "Word.h" 

#define Word_OK (0) 

using namespace std; 

//sets the English word 
void Word::SetEnglish(char *Eng) 
{ 
    English = Eng; 
} 

//gets the English word 
char *Word::GetEnglish() 
{ 
    return English; 
} 

//sets the Finnish word 
void Word::SetFinnish(char *Fin) 
{ 
    Finnish = Fin; 
} 

//gets the Finnish word 
char *Word::GetFinnish() 
{ 
    return Finnish; 
} 

//sets the previous node 
void Word::SetPrev(Word *node) 
{ 
    prev = node; 
} 

//gets the previous node 
Word *Word::GetPrev() 
{ 
    return prev; 
} 

//sets the next node 
void Word::SetNext(Word *node) 
{ 
    next = node; 
} 

//gets the next node 
Word *Word::GetNext() 
{ 
    return next; 
} 

//insert a node after the last node 
int dlist::insertBack (char *Eng, char *Fin) 
{   
    cout << "English: " << Eng << " " << "Finnish :" << Fin << "\n"; 
    if(this->back==NULL) 
    { 
     cout<<"insert at back"; 
     insertFront(Eng, Fin); 
    } 
    else 
    { 
     cout<<"insert at back"; 
     insertAfter(Eng, Fin, this->back ); 
    } 

    return Word_OK; 
} 

//insert a node before the front node 
void dlist::insertFront (char *Eng, char *Fin) 
    { 
    Word *newNode; 
    if(this->front==NULL) 
    { 
     newNode=new Word(); 
     this->front=newNode; 
     this->back =newNode; 
     newNode->SetPrev(NULL); 
     newNode->SetNext(NULL); 
     newNode->SetEnglish(Eng); 
     newNode->SetFinnish(Fin); 
    } 
    else 
    { 
     insertBefore(Eng, Fin, this->front); 
    } 
} 

//insert a node after nodeB 
void dlist::insertAfter(char *Eng, char *Fin, Word *nodeB) 
{ 
    cout << "\nEnglish1: " << Eng << " " << "Finnish1: " << Fin << "\n"; 
    Word *newNode; 
    newNode=new Word(); 
    newNode->SetNext(nodeB->GetNext()) ; 
    newNode->SetPrev(nodeB); 
    newNode->SetEnglish(Eng); 
    newNode->SetFinnish(Fin); 

    if(nodeB->GetNext()==NULL) 
    { 
     cout<<"\n "<< endl; 
     this->back =newNode; 
    } 
    nodeB->SetNext(newNode); 
    cout<<"2"<<endl; 
} 

//insert a node before nodeB 
void dlist::insertBefore(char *Eng, char *Fin, Word *nodeB)  
{ 
    Word *newNode; 
    newNode=new Word(); 
    newNode->SetPrev(nodeB->GetPrev()); 
    newNode->SetNext(nodeB); 
    newNode->SetEnglish(Eng); 
    newNode->SetFinnish(Fin); 
    if(nodeB->GetPrev()==NULL) 
    { 
     this->front=newNode; 
    } 
    nodeB->SetPrev(newNode); 

} 


//Print the list from front 
void dlist::printDListFront() 
{ 
    Word* curr2; 
    curr2= this->front; 
    cout<<"\n------------------------\n"; 
    cout<<"Words in the Dictionary: \n"; 
    cout<<"------------------------\n"; 

    while(curr2!=NULL) 
    { 
     cout<<curr2->GetEnglish(); 
     cout<<" "<< curr2->GetFinnish()<<"\n"; 
     curr2=curr2->GetNext(); 
    } 
    cout<<endl; 
}// print the Double Linked List from front 

main.cpp

#include <iostream> 
#include <fstream> 
#include <cstdlib> 
#include <string.h> 
#include "menu.h" 
#include "Word.h" 

using namespace std; 

#define Word_OK (0) 
#define Word_Not_Found (-1) 
#define Word_already_Exist (-2) 
#define Word_too_big (-3) 
#define Dictionary_empty (-4) 
#define File_error (-5) 
#define Memory_error (-6) 
#define Word_Unknown_Error (-20) 
#define Buffer (200) 
#define Max_len (30) 
#define FILE_NAME "dictionary.txt" 

/* Search the word in the list and print it if found. 
    return an error code if not found or the dictionary is empty. */ 
int SearchWord(); 
/* Add a word in the list from user input. 
    return an error code if the word already exist or if input is too long. */ 
int InsertWord(dlist *w); 
/* Function used by InsertWord() and InitDictionary() to insert a new word in 
    the list at right position (order alphabetically by english word). 
    return an error code if there is a memory allocation problem. */ 
int chainWord(char *en, char *fi, Word *w); 
/* Remove a word from the list. 
    return an error code if word not found. */ 
int DeleteWord(); 
/* Show all the words in the dictionary. This was first a debug function; but 
    since it works, I kept it. Considere that as an extra feature. 
    return an error code if the dictionnary is empty. */ 
int ShowAllWord(dlist *list); 
/* Print error if something goes wrong. */ 
void PrintError(int aErrorCode); 
/* Read the saved words from the file and load it to the dictionary. 
    return an error code if it don't manage to open the file. */ 
int InitDictionary(dlist *list); 
/* Save the words in the file and clean the memory before leaving the program. 
    return an error code if there is a problem with the file. */ 
int ExitDictionary(); 
int putDictionary(Word *w); 

void putword(dlist *st) 
{ 
    char eng[30], fin[30]; 
    cout << "English word: " ; 
    cin >> eng; 
    cout << "Finnish word: "; 
    cin >> fin; 
    st->insertBack(eng, fin); 
} 

void main() 
{ 
    char eng[30], fin[30]; 

    dlist *st ; 
    st= new dlist(); 
    cout << "English word: " ; 
    cin >> eng; 
    cout << "Finnish word: "; 
    cin >> fin; 
    st->insertBack(eng, fin); 
    st->insertBack("hello", "hei"); 
    st->insertBack("we", "me"); 
    st->insertBack("they", "he"); 
    st->insertBack("truck", "rekka") ; 
    st->printDListFront(); 

    Menu m; 
    m.PrintHeader(); 
    m.PrintMenu(); 
    //PrintError(InitDictionary(st)); 
    int errorcode = 0; 
    char c; 
    cout << "Choose option: "; 
    cin >> c; 
    fflush(stdin); //I want one option at the time, so flush the end of line 
    while(c != 'e' && c != 'E'){ 
     switch(c){ 
      case 's': 
      case 'S': 
       // errorcode = SearchWord(); 
       break; 
      case 'i': 
      case 'I': 
        putword(st); 
       break; 
      case 'd': 
      case 'D': 
       // errorcode = DeleteWord(); 
       break; 
      case 'a': 
      case 'A': 
       errorcode = ShowAllWord(st); 
       break; 
      default: 
       system("cls"); 
       m.PrintMenu(); 
     } 
     PrintError(errorcode); 
     cout << "Choose option: "; 
     cin >> c; 
     fflush(stdin); 
    } 
    //PrintError(ExitDictionary()); 


    system("pause"); 
} 


int InsertWord(dlist *list) 
{ 
    char eng[30], fin[30]; 

    cout << "English word: " ; 
    cin >> eng; 
    cout << "Finnish word: "; 
    cin >> fin; 

    int res = list->insertBack(eng, fin); 

    return res; 
} 

int ShowAllWord(dlist *list) 
{ 
    list->printDListFront(); 
    return 0; 
} 

void PrintError(int aErrorCode){ 
    switch(aErrorCode){ 
     case Word_OK: 
      break; 
     case Word_Not_Found: 
      cout << "Word not found!" << endl; 
      break; 
     case Word_already_Exist: 
      cout << "The word already exist!" << endl; 
      break; 
     case Word_too_big: 
      cout << "The word is too big!" << endl; 
      break; 
     case Dictionary_empty: 
      cout << "Dictionary is empty!" << endl; 
      break; 
     case File_error: 
      cout << "Error with file!" << endl; 
      break; 
     case Memory_error: 
      cout << "Memory allocation problem!" << endl; 
      break; 
     case Word_Unknown_Error: 
     default: 
      cout << "Oppps Unknown Error!" << endl; 
      break; 
    }      
} 

menu.h

#ifndef _MENU_H_ 
#define _MENU_H_ 

//this class was created as an exercise and also to reduce the size of code of 
//the main. 
class Menu{ 
    public: 
     /*print the information about the program and the author.*/ 
     void PrintHeader(); 
     /*print the options for the user.*/ 
     void PrintMenu(); 
}; 

#endif  

menu.cpp

#include <iostream> 
#include "menu.h" 

using namespace std; 
/* Implementation of the menu class. */ 
void Menu::PrintHeader(){ 
    cout << "*************************************" << endl 
      << "****  Dictionary    ****" << endl 
      << "****  By Your Name and ID ****" << endl; 
} 

void Menu::PrintMenu(){ 
    cout << "*************************************" << endl 
      << "***    MENU    ***" << endl 
      << "*************************************" << endl 
      << "S - Search"   << endl 
      << "I - Insert"   << endl 
      << "D - Delete"   << endl 
      << "A - Show all words" << endl 
      << "E - Exit"   << endl 
      << " - Any other key to clear the screen" << endl 
      << "*************************************" << endl; 
} 
+0

Объясните, что вы подразумеваете под «полным мусора». –

+0

Проблема заключается в том, что вы используете автоматические массивы, выходящие из области видимости и использующие повторно, вместо того, чтобы размещать или расширять пространство, которое находится вокруг. –

+1

Похоже, вы используете 'char *', где вы имеете в виду 'std :: string &'. – Johnsyweb

ответ

1
char eng[30], fin[30]; 

cout << "English word: " ; 
cin >> eng; 
cout << "Finnish word: "; 
cin >> fin; 

int res = list->insertBack(eng, fin); 

Вы можете использовать локальные массивы insertBack аргумента, а также класс Слово имеет указатель на них. Они выйдут из области действия, как только функция завершится, и после этого значение может быть чем угодно. То, что вы должны хранить в классе Word, является копией строки в ее собственном хранилище (динамически или статически).

+2

Как использовать 'std :: string', который обрабатывает все это автоматически. –

+0

@BoPersson: действительно – LeleDumbo

+0

Итак, позвольте мне посмотреть, следую ли вы тому, что вы говорите. Я понимаю о локальном использовании, но не уверен, что вы имеете в виду копию строки в классе. Поэтому в моем классе это должно быть похоже на струнный английский; и строка финский; вместо чата * Английский? – Xintaris

Смежные вопросы