2015-10-13 2 views
0

Я хочу разработать программу BST, которая загружает и сохраняет контактные данные, которые являются именем, номером телефона и электронной почтой из/в text.file.PhoneEntry: Binary Search Tree C++ program

В настоящее время я могу хранить, загружать, вставлять, удалять и печатать имя вместе с его номером телефона. Но после того, как я улучшил код, добавив еще одну информацию, которая является электронной почтой, программа BST получает беспорядок.

Прежде чем объяснить о проблеме, что я получил, пожалуйста, посмотрите сначала на мой phonebook.txt: enter image description here

Хотя ниже это мой выход программы BST. enter image description here

Из приведенного выше результата проблема заключается в том, что программа считывает электронное письмо как имя. Но программа по-прежнему считывает номер телефона в качестве номера телефона. И электронная почта не отображается/не объявляется вообще? И я не знаю, куда пошло настоящее имя?

Для получения ясно, давайте посмотрим на вывод всех контактов в phonebook.txt по выбрать 2. Все контакты Информация из программы enter image description here

Там нет имени (Адам, Фарис, ТНБ. ...). Но электронная почта (например: [email protected]) была прочитана как имя ..

я получил оригинальную BST программы (имя + PHONENUMBER) от https://www.daniweb.com/programming/software-development/threads/327525/binary-search-tree-file-reading

Тогда я повысил код, добавив адрес электронной части. Вот мой код:

//Binary Search Tree Program 
#include <iostream> 
#include <cstdlib> 
#include <fstream> 
#include <iomanip> 
#include <stdio.h> 
using namespace std; 
//typedef string ItemType; 
class Person{ 
    private: 
    string name; 
    int phonenumber; 
    string email; 
    public: 
    Person(); 
    Person(string name, int phonenumber, string email); 
    string getName(); 
    int getPhonenumber(); 
    string getEmail(); 
    void setName(string newname); 
    void setPhonenumber(int newphonenumber); 
    void setEmail(string newemail); 
}; 
class BinarySearchTree 
{ 
    private: 
     struct tree_node 
     { 
      tree_node* left; 
      tree_node* right; 
      //ItemType data; 
      Person data; 
     }; 
     tree_node* root; 
    public: 
     BinarySearchTree() 
     { 
      root = NULL; 
     } 
     bool isEmpty() const { return root==NULL; } 
     void print_inorder(); 
     void inorder(tree_node*); 
     void insert(Person); 
     void remove(string); 
     void search(string key); 
     void changePhonenumber(string key, int newnumber); 
}; 
Person::Person() 
{ 
} 
Person::Person(string newname, int newphonenumber, string newemail) 
{ 
    name = newname; 
    phonenumber = newphonenumber; 
    email = newemail; 
} 
string Person::getName() { 
    return name; 
} 
int Person::getPhonenumber() { 
    return phonenumber; 
} 
string Person::getEmail() { 
    return email; 
} 
void Person::setName(string newname) { 
    name = newname; 
} 
void Person::setPhonenumber(int newphonenumber) { 
    phonenumber = newphonenumber; 
} 
void Person::setEmail(string newemail) { 
    name = newemail; 
} 
// Smaller elements go left 
// larger elements go right 
void BinarySearchTree::insert(Person p) 
{ 
    tree_node* t = new tree_node; 
    tree_node* parent; 
    t->data = p; 
    t->left = NULL; 
    t->right = NULL; 
    parent = NULL; 
    // is this a new tree? 
    if(isEmpty()) root = t; 
    else 
    { 
     //Note: ALL insertions are as leaf nodes 
     tree_node* curr; 
     curr = root; 
     // Find the Node's parent 
     while(curr) 
     { 
      parent = curr; 
      if(t->data.getName() > curr->data.getName()) curr = curr->right; 
      else curr = curr->left; 
     } 
     if(t->data.getName() < parent->data.getName()) 
      parent->left = t; 
     else 
      parent->right = t; 
    } 
} 
void BinarySearchTree::remove(string p) 
{ 
    //Locate the element 
    bool found = false; 
    if(isEmpty()) 
    { 
     cout<<" This Tree is empty! "<<endl; 
     return; 
    } 
    tree_node* curr; 
    tree_node* parent; 
    curr = root; 
    while(curr != NULL) 
    { 
     if(curr->data.getName() == p) 
     { 
      found = true; 
      break; 
     } 
     else 
     { 
      parent = curr; 
      if(p>curr->data.getName()) curr = curr->right; 
      else curr = curr->left; 
     } 
    } 
    if(!found) 
     { 
     cout<<" Data not found! "<<endl; 
     return; 
    } 
     // 3 cases : 
    // 1. We're removing a leaf node 
    // 2. We're removing a node with a single child 
    // 3. we're removing a node with 2 children 
    // Node with single child 
    if((curr->left == NULL && curr->right != NULL)|| (curr->left != NULL 
&& curr->right == NULL)) 
    { 
     if(curr->left == NULL && curr->right != NULL) 
     { 
      if(parent->left == curr) 
      { 
      parent->left = curr->right; 
      delete curr; 
      } 
      else 
      { 
      parent->right = curr->right; 
      delete curr; 
      } 
     } 
     else // left child present, no right child 
     { 
      if(parent->left == curr) 
      { 
      parent->left = curr->left; 
      delete curr; 
      } 
      else 
      { 
      parent->right = curr->left; 
      delete curr; 
      } 
     } 
    return; 
    } 
     //We're looking at a leaf node 
     if(curr->left == NULL && curr->right == NULL) 
    { 
     if(parent->left == curr) parent->left = NULL; 
     else parent->right = NULL; 
       delete curr; 
       return; 
    } 
    //Node with 2 children 
    // replace node with smallest value in right subtree 
    if (curr->left != NULL && curr->right != NULL) 
    { 
     tree_node* chkr; 
     chkr = curr->right; 
     if((chkr->left == NULL) && (chkr->right == NULL)) 
     { 
      curr = chkr; 
      delete chkr; 
      curr->right = NULL; 
     } 
     else // right child has children 
     { 
      //if the node's right child has a left child 
      // Move all the way down left to locate smallest element 
      if((curr->right)->left != NULL) 
      { 
       tree_node* lcurr; 
       tree_node* lcurrp; 
       lcurrp = curr->right; 
       lcurr = (curr->right)->left; 
       while(lcurr->left != NULL) 
       { 
        lcurrp = lcurr; 
        lcurr = lcurr->left; 
       } 
     curr->data = lcurr->data; 
       delete lcurr; 
       lcurrp->left = NULL; 
      } 
      else 
      { 
       tree_node* tmp; 
       tmp = curr->right; 
       curr->data = tmp->data; 
      curr->right = tmp->right; 
       delete tmp; 
      } 
     } 
     return; 
    } 
} 
void BinarySearchTree::print_inorder() 
{ 
    inorder(root); 
} 
void BinarySearchTree::inorder(tree_node* p) 
{ 

    if(p != NULL) 
    { 
     if(p->left) inorder(p->left); 
     cout<<" "<<p->data.getName()<<"\t\t"<<p->data.getPhonenumber()<<"\t\t"<<p->data.getEmail()<<endl; 
     if(p->right) inorder(p->right); 
    } 
    else return; 
} 

//////////////////new///////////////////////// 
void BinarySearchTree::search(string key) 
{ 
    bool found = false; 
    if(isEmpty()) 
    { 
     cout<<" This Tree is empty! "<<endl; 
     return; 
    } 
    tree_node* curr; 
    tree_node* parent; 
    curr = root; 
    while(curr != NULL) 
    { 
     if(curr->data.getName() == key) 
     { 
      found = true; 
      cout << "The phone number for " << key << " is " << curr->data.getPhonenumber() << endl; 
      break; 
     } 
     else 
     { 
      parent = curr; 
      if(key>curr->data.getName()) curr = curr->right; 
      else curr = curr->left; 
     } 
    } 
    if(!found) 
     { 
     cout<<" Data not found! "<<endl; 
     return; 
    } 
} 
void BinarySearchTree::changePhonenumber(string p, int newnumber) { 
    bool found = false; 
    if(isEmpty()) 
    { 
     cout<<" This Tree is empty! "<<endl; 
     return; 
    } 
    tree_node* curr; 
    tree_node* parent; 
    curr = root; 
    while(curr != NULL) 
    { 
     if(curr->data.getName() == p) 
     { 
      found = true; 
      break; 
     } 
     else 
     { 
      parent = curr; 
      if(p>curr->data.getName()) curr = curr->right; 
      else curr = curr->left; 
     } 
    } 
    if(!found) 
     { 
     cout<<" Person not found. "<<endl; 
     return; 
    } 
    //change the phonenumber associated with the node 
    curr->data.setPhonenumber(newnumber); 
    cout<< "Number changed successfully. " << endl; 
}//end changePhonenumber 
/////////////////////////////////////new add into book class////////////// 
//void fillTree(BinarySearchTree b) 
void fillTree(BinarySearchTree *b)//Line 368 
{ 
    ifstream file; 
    file.open("phonebook.txt"); 
    if(!file) { 
     cout<<" Error opening file. " << endl; 
    } 
    //variables used to load data into the tree 
    string name; 
    int phonenumber; 
    string email; 
    Person p; 
    while(file >> name >> phonenumber >> email) 
    { 
     p.setName(name); 
     p.setPhonenumber(phonenumber); 
     p.setEmail(email); 
     cout << p.getName() << " " << p.getPhonenumber() << " " <<p.getEmail()<< endl; 
     //b.insert(p); 
     (*b).insert(p); //Line 384 
    } 
    file.close(); 
} 
int main() 
{ 
    BinarySearchTree b; 
    int ch; 
    string name; 
    string key; 
    int phonenumber; 
    string email; 
    Person tmp; 
    Person tmp1; 

    fillTree(&b); // Line 398//print the contents of phonebook.txt 
    while(1) 
    { 
     cout<<endl<<endl; 
     cout<<" Binary Search Tree Operations "<<endl; 
     cout<<" ----------------------------- "<<endl; 
     cout<<" 0. Search    "<<endl; 
     cout<<" 1. Insertion/Creation "<<endl; 
     cout<<" 2. All Contacts Information "<<endl; 
     cout<<" 3. Removal "<<endl; 
     cout<<" 4. Change a Phonenumber "<<endl; 
     cout<<" 5. Exit "<<endl; 
     cout<<" Enter your choice : "; 
     cin>>ch; 
     switch(ch) 
     { 
      case 0 : cout <<" Enter the name of the person to search for: "<<endl; 
        cin>>key; 
        b.search(key); 
        break; 
      case 1 : cout<<" Enter name to be inserted: "; 
        cin>>name; 
        cout << endl << " Enter phone number: " << endl; 
        cin >> phonenumber; 
        cout<<" Enter email: "; 
        cin>>email; 
        tmp.setName(name); 
        tmp.setPhonenumber(phonenumber); 
        tmp.setEmail(email); 
        b.insert(tmp); 
        break; 
      case 2 : cout<<endl; 
        cout<<" All Contacts Information "<<endl; 
        cout<<" ------------------------"<<endl; 
        cout<<" NAME\t\tPHONE\t\tEMAIL"<<endl; 
        b.print_inorder(); 
        break; 
      case 3 : cout<<" Enter data to be deleted : "; 
        //cout << "Deletion needs to be implemented." << endl; 
        cin>>key; 
        b.remove(key); 
        break; 
      case 4 : cout<<" Enter the name of the person whose number you wish to change: " <<endl; 
        cin>>name; 
        cout<<endl<<" Enter the new phonenumber: " <<endl; 
        cin>>phonenumber; 
        cout<<endl; 
        b.changePhonenumber(name, phonenumber); 
        break; 
      case 5 : return 0; 

     } 
    } 
} 

ответ

0
void Person::setEmail(string newemail) { 
    name = newemail;//setting the wrong value happens here 
} 

должен быть изменен на

void Person::setEmail(string newemail) { 
    email = newemail; 
}