next up previous contents
Next: The Bag Classes: Up: The Node Class: Previous: node.h:

node.c:

#include <string.h>
#include <iostream.h>
#include "node.h"

istream& operator>>(istream& in, Node& A)
  {A.grab(in); return(in);}
istream& operator>>(istream& in, Node* A)
  {A->grab(in); return(in);}
ostream& operator<<(ostream& out,const Node& A)
  {A.print(out); return(out);}
ostream& operator<<(ostream& out,const Node* A)
  {A->print(out); return(out);}
istream& Node::grab(istream& input)
{
  const int MAX_LENGTH = 100;
  int count;
  char buffer[MAX_LENGTH]; 
  char c,d; 
  cout << "Please enter the character that will"
       << " terminate the input string you want to use"
       << " for a name"  << endl;
  input >> c;
  cout << "Now enter the name you want to use for the node:" << endl;
  input >> d;
  count = 0;
  while(d!=c){
    buffer[count++] = d;
    input >> d;
    }
  //word finished
  d_name_p = new char[count+1];
  for(int i=0;i<count;i++)
    d_name_p[i] = buffer[i];
  //now null terminate string
  d_name_p[count] = '\0';
  return input;
}

ostream& Node::print(ostream& output) const
{
  output << d_name_p << endl;
  return output;
}
Node::Node(){d_name_p = NULL;}
Node::Node(const char *name)
{
  d_name_p = new char[strlen(name)+1];
  strcpy(d_name_p,name);
}
Node::Node(const Node& T)
{
  d_name_p = new char[strlen(T.d_name_p)+1];
  strcpy(d_name_p,T.d_name_p);
}
Node::~Node()
{
  if(d_name_p!=NULL)
    delete [] d_name_p;
}
Node& Node::operator=(const Node& T)
{
  if(&T!=this){
    if(d_name_p!=NULL)
      delete [] d_name_p;
    d_name_p = new char[strlen(T.d_name_p)+1];
    strcpy(d_name_p,T.d_name_p);
    return *this;     
    }
  else
    return *this;
}
const char* Node::name() const
{
  char *name;
  name = new char[strlen(d_name_p)+1];
  strcpy(name,d_name_p);
  return name;
}



Jim Peterson
1999-05-17