Simple Tree in VC++

Simple Tree in Visual C++

This code was compiled and tested on a Windows.

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code is given ‘as is’. I do not take responsibilities of how they are used.

mainTree.cpp:

#include 'standard.h'
#include 'tree.h'

using namespace std;

//Print the divider to the specified file
void PrintDivider ( ofstream& fout,
				    char symbol,
					int numOfSymbols,
					int section );

//Print the count to the specified file
void PrintCount ( ofstream& fout,
				  int count );

int main(void)
{
	//declare the files
	ifstream fin;
	ofstream fout;

	//Set the task number to -1
	int section = -1;

	//Open the files
	fin.open('tree.txt');
	fout.open('treeOut.txt');

	//Create an instance of the class
	TreeClass tree;

	//Declare variables
	int numOfNodesInTree;

	//print empty tree message
	tree.PrintTree ( fout );
	PrintDivider ( fout,
		           '*',
				   63,
				   section++);

	//Insert values from the input file
	tree.CreateATree ( fin );

	//Print the tree nodes on one line
	tree.PrintTree ( fout );
	PrintDivider ( fout,
		           '*',
				   63,
				   section++);

	//Calculate the number of nodes in the tree
	numOfNodesInTree = tree.CountNodesInTree();

	//Print the count
	PrintCount ( fout,
		         numOfNodesInTree );
	fout << endl;

	//Close the files
	fin.close();
	fout.close();

	return 0;
}

//Print the divider to the specified file
void PrintDivider ( ofstream& fout,
				    char symbol,
					int numOfSymbols,
					int section )
{
	fout << endl << endl;
	fout << '#' << setw(2)<< section << BLANK;
	fout.fill( symbol );
	fout << setw( numOfSymbols ) << BLANK;
	fout << endl;
	fout.fill( BLANK );
	fout << setw(3)<<BLANK;

}

//Print the count to the specified file
void PrintCount ( ofstream& fout,
				  int count )
{
	fout << ' Number of Nodes currently in the tree are: '
		 << count << endl;

}

standard.h:

#ifndef standard_h

#define standard_h

#include <iostream>

#include <iomanip>

#include <fstream>

using namespace std;

const char BLANK = ' ';

#endif

tree.h:

#ifndef tree_h

#define tree_h

#include 'standard.h'

struct nodeType

{

	int value;

};

struct treeType

{

	nodeType  data;

    treeType* left;

	treeType* right;

};

typedef treeType* treePtr;

class TreeClass

{ 

	private:

		treePtr root;

		//Insert the node in ascending order

		void InsertNode ( treePtr& ptr,

		                  nodeType aNode );

		//Create memory, insert data into a tree node

		treePtr GetANode ( nodeType ANode );

		//Delete a leaf node from a tree, free the memory

		void DeleteLeaf( treePtr location, 

					     treePtr& parent );

		//Delete a node with one left child only

		void DeleteLeft ( treePtr location,

					      treePtr& parent );

		//Delete a node with one right child only

		void DeleteRight ( treePtr location,

						   treePtr& parent );

		//Delete a node that has two children

		void DeleteTwoChildren( treePtr& location );

		//Called recursively to visit each node in the tree InOrder

		void InOrder ( ofstream& fout,

			           treePtr ptr );

		//Called recursively to visit each node in the tree PreOrder

		void PreOrder ( ofstream& fout,

			            treePtr ptr );

		//Called recursively to visit each node in the tree PostOrder

		void PostOrder ( ofstream& fout,

			             treePtr ptr );

		//Count the nodes in the tree

		void CountNodes ( treePtr ptr,

			              int& count );

	public:

		//Constructor

		TreeClass( void );

		//Create a tree from an input file

		void CreateATree ( ifstream& fin );

		//Return a bool based on value of root

		bool EmptyTree() const;

		//Print Tree content to an output file

		void PrintTree ( ofstream& fout );

		//Count the nodes in a tree

		int CountNodesInTree ( void );

		//Delete a node in the tree, return success of delete

		bool Delete ( int num );

		//Insert a node in Order in a tree

		void Insert ( nodeType node );

		//Print tree in PreOrder

		void PrintPreOrder ( ofstream& fout );

		//Print tree in PostOrder

		void PrintPostOrder ( ofstream& fout );

		//Search the tree for a num, return the node, the parent and a flag

		void Search ( treePtr& ptr,

			          treePtr& parent,

					  int num,

					  bool& success );

		//The destructor, free the memory

		~TreeClass ( void );

};

#endif

TreeFunctions.cpp:

#include 'tree.h'
///Add your methods HERE

///Private Methods ------------------------------------------------------------------------///

//Insert the node in ascending order
void TreeClass::InsertNode ( treePtr& ptr,
				             nodeType aNode )
{
	//if this is the first node
	if ( ptr == NULL )
	{

		ptr = GetANode ( aNode );

	}
	//is the value less than current ptr value, insert to the left
	else if ( aNode.value < ptr->data.value )
	{
		InsertNode ( ptr->left, aNode );
	}
	//if the value greater than the current ptr value,insert to the right
	else
	{
		InsertNode ( ptr->right, aNode );
	}
}

//Create memory, insert data into a tree node
treePtr TreeClass::GetANode ( nodeType aNode )
{
	treePtr ptr;

	//Create a new tree node
	ptr = new treeType;

	//Put the data into the tree node
	ptr->data = aNode;

	//Set the pointers of this new leaf node
	ptr->left = NULL;
	ptr->right = NULL;

	return ptr;
}

//Delete a leaf node from a tree, free the memory
void TreeClass:GrineleteLeaf( treePtr location,
						    treePtr& parent )
{
	//Check to see if it is the root
    if ( parent == NULL )
	{
		root = NULL;
	}
	else if (parent->right == location)
	{
		//right child, sever connection
		parent->right = NULL;
	}
    else
	{
		//left child, sever connection
        parent->left = NULL;
	}

	//free the memory
	delete location;
}

//Delete a node with one left child only
void TreeClass:GrineleteLeft ( treePtr location,
						     treePtr& parent )
{
	//Check to see if it is the root
	if ( parent == NULL )
	{
		//Make left child the root
		root = location->left;
	}
	else if ( parent->left == location )
	{
		//left child, re-connect to it's left
		parent->left = location->left;
	}
	else
	{
		//right child, re-connect to it's right
		parent->right = location->left;
	}

	//Set left pointer to NULL
	location->left = NULL;

	//Free the memory
	delete location;
}

//Delete a node with one right child only
void TreeClass:GrineleteRight( treePtr location,
						     treePtr& parent )
{
	//Check to see if it is the root
	if ( parent == NULL )
	{
		//Set root to the right child
		root = location->right;
	}
	else if ( parent->right == location )
	{
		//right child, re-connect right
		parent->right = location->right;
	}
    else
	{
		//left child, re-connect left
		parent->left = location->right;
	}

	//Set right pointer to NULL
	location->right = NULL;

	//Free the memory
	delete location;
}

//Delete a node that has two children
void TreeClass:GrineleteTwoChildren( treePtr& location )
{

	treePtr place;
	treePtr walker;

	//Go left once
	place = location->left;

	//Check right, if NULL stop
	if ( place->right == NULL )
	{// found a place
		//move the data into location
		location->data = place->data;

		//Set the pointer of location left to place's left
		location->left = place->left;

	}// found a place

	else
	{// walk through tree
		do
		{
			// find node without right child
			walker = place;

			//Keep going right
			place = place->right;
		}while ( place->right!=NULL );

		//move the data into location
		location->data = place->data;

		//connect left child of place to right of walker
		walker->right = place->left;

	}// walk through tree

	//set place's pointer to NULL
	place->left = NULL;

	//Free the memory
	delete place;
}

//Called recursively to visit each node in the tree InOrder
void TreeClass::InOrder( ofstream& fout,
					     treePtr ptr )
{
	//There is still a node in the tree
	if ( ptr != NULL )
	{
		//Go left
		InOrder( fout,
		         ptr->left );

		//Print this node
		fout << setw(3) << ptr->data.value;

		//Go right
		InOrder( fout,
		         ptr->right );
   }
}

//Called recursively to visit each node in the tree PreOrder
void TreeClass:RazzreOrder ( ofstream& fout,
						   treePtr ptr )
{
	//There is still a node in the tree
	if ( ptr != NULL )
	{
		//Print this node
		fout << setw(3) << ptr->data.value;

		//Go left
		PreOrder( fout,
		          ptr->left );

		//Go right
		PreOrder( fout,
		          ptr->right );

   }
} 

//Called recursively to visit each node in the tree PostOrder
void TreeClass:RazzostOrder ( ofstream& fout,
						    treePtr ptr )
{
	//There is still a node in the tree
	if ( ptr != NULL )
	{
		//Go left
		PostOrder( fout,
		           ptr->left );

		//Go right
		PostOrder( fout,
		           ptr->right );

		//Print the node
		fout << setw(3) << ptr->data.value;
   }
}

//Count the nodes in the tree
void TreeClass::CountNodes ( treePtr ptr,
						     int& count )
{
	//There is still a node in the tree
	if ( ptr !=NULL )
	{
		//Increment the count
		count++;

		//Go left
		CountNodes ( ptr->left,
			         count );

		//Go right
		CountNodes ( ptr->right,
			         count );
	}
}
///Public Methods ------------------------------------------------------------------------///
//Constructor
TreeClass::TreeClass()
{
	root = NULL;
}

//Create a tree from an input file
void TreeClass::CreateATree ( ifstream& fin )
{
	nodeType node;

	//while there is data in the input file
	while ( !fin.eof() )
	{
		//read a value
		fin >> node.value;

		//Insert the value into the tree
		Insert( node );
	}
}

//Return a bool based on value of root
bool TreeClass::EmptyTree() const
{
	return ( root == NULL );
}

//Print Tree content to an output file
void TreeClass:RazzrintTree ( ofstream& fout)

{
	//Set a node to the root
	treePtr ptr = root;

	//if null, tree is empty
	if (ptr == NULL)
	{
		fout<< 'Tree is empty' << endl;
	}
	else
	{
		//Call Inorder Print of tree
		InOrder ( fout,
	              ptr );
	}	           

}

//Count the nodes in a tree
int TreeClass::CountNodesInTree ( void )
{
	//Set a pointer to the root
	treePtr ptr = root;

	//Initialize the count
	int count = 0;

	//Call the recursive method to count the nodes in the tree
	CountNodes ( ptr,
		         count );

	return count;
}

//Delete a node in the tree, return success of delete
bool TreeClass:Grinelete ( int num )
{
	//Set a pointer to the root
	treePtr ptr = root;

	//Parent of root is null
	treePtr parent = NULL;

	bool success ;

	//Call recursive search method
	Search ( ptr,
		     parent,
			 num,
			 success );

	//If it was successful, node was found
	if ( success )
	{
		//Is it a leaf node?
		if ( ptr->left == NULL && ptr->right == NULL )
		{
			//Delete the leaf
			DeleteLeaf ( ptr,
				         parent );
		}
		//This is a node with only a left child
		else if ( ptr->left !=NULL && ptr->right == NULL )
		{
			//Delete a node with a left child
			DeleteLeft ( ptr,
				         parent );
		}
		//This is a node with a right child
		else if ( ptr->left == NULL && ptr->right != NULL )
		{
			//Delete a node with a right child
			DeleteRight ( ptr,
				          parent );
		}
		//it must be a node with two children
		else
		{
			//Delete a node with two children
			DeleteTwoChildren ( ptr );
		}
	}

	return success;
}

//Insert a node in Order in a tree
void TreeClass::Insert ( nodeType node )
{
	//Set a pointer to the root
	treePtr ptr = root;

	//Call the recursive method to insert a node
	InsertNode ( ptr,
		         node );

	//if this is the first node,set the root to the new node
	if ( EmptyTree())
	{
		root = ptr;
	}
}

//Print tree in PreOrder
void TreeClass:RazzrintPreOrder ( ofstream& fout )
{
	//Call the recursive method for PreOrder
	PreOrder ( fout,
		       root );
}

//Print tree in PostOrder
void TreeClass:RazzrintPostOrder ( ofstream& fout )
{
	//Call the recursive method for PostOrder
	PostOrder ( fout,
		        root );
}

//Search the tree for a num, return the node, the parent and a flag
void TreeClass::Search ( treePtr& ptr,
						 treePtr& parent,
						 int num,
						 bool& success )
{
	//Node was not found yet
	success = false;

	//while there are still nodes to search and node value was not found
	while ( ptr !=NULL && !success )
	{
		//If the node value in the tree is the value you are searching for
		if ( ptr->data.value == num )
		{
			//you found it
			success = true;
		}
		//if the node value in the tree is less than the value you are searching for
		else if ( num < ptr->data.value )
		{
			//Set the parent to the current ptr in the tree
			parent = ptr;

			//Move to the left
			ptr = ptr->left;
		}
		else
		{
			//Set the parent to the current ptr in the tree
			parent = ptr;

			//Move to the right
			ptr = ptr->right;
		}
	}
}

//The destructor, free the memory
TreeClass::~TreeClass ( void )
{
	//while the tree is not empty
	while ( !EmptyTree())
	{
		//Delete the node at the root
		Delete ( root->data.value );
	}
}

tree.txt:

48
12
56
2
9
18
52
49
10
-5
55
5
59
57
58
9
65
41
18
42

If you encounter any problems or errors, please let me know by providing an example of the code, input, output, and an explanation. Thanks.

Share
Leave a comment

Example of Linked List as Template

Example of Linked List as Template.

This code was compiled and tested on a Linux machine

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code is given ‘as is’. I do not take responsibilities of how they are used.

List.cc:

#ifndef LIST_CC
#define LIST_CC

#include <iostream>

using namespace std;

template <typename T>
class Node {

	public:

		// Create a linked list node by setting its data to the input parameter
		// and the next node in the linked list to NULL (0)
		Node(const T& data_input);

		//The default constructor doesn't initialize the data members
		Node();

		//The default destructor doesn't initialize the data members
		~Node();

		// Contains the data of the linked list node
		T data;	

		// Contains a pointer to the next item in the linked list
		Node<T> *next;

		// Contains a pointer to the previous item in the linked list
		Node<T> *previous;

};

template <typename T>
class List {
	private:

		// Contains a pointer to the first node in the
		// linked list (the head of the list)
		Node<T> *head;	

		// Contains a pointer to the last node in the
		// linked list (the head of the list)
		Node<T> *tail;

		int num_elements;

	public:

		// Create a Linked list by initializing it's head to NULL (0)
		List(void);

		List(const List<T>& list);

		// Delete all the elements in the linked list when the list is deleted
		~List(void);

		bool isempty() const;

		// Takes an item as a parameter, appends that item to
		// the front of the list, and returns the list
		List<T> *addtofront(const T& data_input);

		// Takes an item as a parameter, appends that item to
		// the back of the list, and returns the list
		List<T> *addtoback(const T& data_input);

		// Returns a pointer to a copy of the first item in the list,
		// leaving it in the list
		Node<T> *getfirst() const;

		int size() const;

		// Takes no parameters, and returns a list containing
		// all but the first element of the list
		List<T> *getrest() const;

		// Print all the elements in the linked list
		void show();

};

// -------------------------------------
// ------------Node class---------------
// -------------------------------------

//
// Create a linked list node by setting its data to the input parameter
// and the next node in the linked list to NULL (0)
template <typename T>
Node<T>::Node(const T& data_input) {

   data = data_input;

    next = NULL;

    previous = NULL;

}

// Default constructor leaves data items unspecified
template <typename T>
Node<T>::Node() {

    next = NULL;

    previous = NULL;
}

// Default constructor leaves data items unspecified
template <typename T>
Node<T>::~Node() {
}

// -------------------------------------
// ------------List class---------------
// -------------------------------------

//
// Default constructor creates an empty list
//
template <typename T>
List<T>::List(void) {

    head = NULL;

	tail = NULL;

    num_elements = 0;

}

template <typename T>
List<T>::List(const List<T>& list){

    if ( list.head != NULL ){

		Node<T> *current_node = list.head;

		while (current_node != NULL){

			addtoback(current_node->data);

			current_node = current_node->next;

			num_elements++;
		}
	}
}

//
// Delete all the elements in the linked list when the list is deleted
//
template <typename T>
List<T>::~List(void) {

   Node<T> *next_node;

    Node<T> *current_node = head;

    while (current_node != NULL) {

       	next_node = current_node->next;

        delete(current_node);

        current_node = next_node;

    }	

}

template <typename T>
bool List<T>::isempty() const{
	return((num_elements < 1));
}

template <typename T>
int List<T>::size() const{
	return num_elements;
}

// Takes an item as a parameter, appends that item to
// the front of the list, and returns the list
template <typename T>
List<T> *List<T>::addtofront(const T& data_input){

    Node<T> *new_node;

    new_node = new Node<T>;

    new_node->data = data_input;

	// If list_head == 0 then assign new_node as the list_head
	// else point new_node->next to list_head. After make that
	// new node the list_head
    if (head == NULL) {

        head = new_node;

        tail = new_node;

    } else {

        new_node->next = head;

        head = new_node;	

    }

    num_elements++;

	return (this);
}

// Takes an item as a parameter, appends that item to
// the back of the list, and returns the list
template <typename T>
List<T> *List<T>::addtoback(const T& data_input){

    Node<T> *new_node;

    new_node = new Node<T>;

    new_node->data = data_input;

    if (tail == NULL) {

        tail = new_node;

	    if (head == NULL) {

	        head = new_node;

	    } else {

	        new_node->next = head;

	        head = new_node;	

	    }

    } else {

		tail->next = new_node;

		new_node->previous = tail;

		tail = new_node;

    }

    num_elements++; 

    //delete(new_node);

	return (this);
}

// Returns a pointer to a copy of the first item in the list,
// leaving it in the list
template <typename T>
Node<T> *List<T>::getfirst() const{
	return (new Node<T>(head->data));
}

// Takes no parameters, and returns a list containing
// all but the first element of the list
template <typename T>
List<T> *List<T>::getrest() const{

	List<T> *rlist = new List<T>();

	Node<T> *current_node;

	if (head->next != NULL){

		current_node = head->next;

		while (current_node != NULL){

			rlist->addtoback(current_node->data);

			current_node = current_node->next;
		}
	}

	return (rlist);
}

//
// Print all the elements in the linked list
//
template <typename T>
void List<T>::show() {

    cout << 'List of ' << num_elements << ' elements: ' ;

    Node<T> *current_node = head;

    while (current_node != NULL) {

        cout << current_node->data << ' ';

        current_node = current_node->next;

    }

    cout << endl;
}

#endif

MainDriver.cpp

#include <iostream>
#include <string>
#include 'List.cc'

using namespace std;

template <typename T>
List<T> *reverse(List<T>& list);

int main (int argc, char *argv[]) {

	List<string> my_list;

	List<string> *my_list_2;

	cout << endl << 'BUILD ORIGINAL---------------------------' << endl;

	my_list.addtoback('one(1)');
	my_list.addtofront('nine(9)');
	my_list.addtoback('eight(8)');

	my_list.show();

	cout << endl << 'REVERSE ORIGINAL---------------------------' << endl;

	my_list_2 = reverse<string>(my_list);

	cout << endl << 'New: ';

	my_list_2->show();

	delete my_list_2;

	return 0;
}

// Write a templated reverse() function
// (not a member function of your class, but instead
// a standalone templated function)
// that operates on a doubly linked list object
// (that you implemented for Part 1).
// Your reverse function should take as input a
// doubly linked list object,
// and return a copy of the list,
// but in reverse order. 

// Your function must be recursive,
// and must use the four functions above.

// A reversed list can be built by taking an element off one side,
// reversing the list without that element in it,
// and then putting that element back into the list,
// on the other side.... use that reasoning to design your recursive
// reverse function. 

template <typename T>
List<T> *reverse(List<T>& list){		

	if (list.size() < 1){

		List<T> *rlist = new List<T>;

		return (rlist);

	}else{

		Node<T> *node;

		List<T> *rlist = new List<T>;

		node = list.getfirst();

		rlist = list.getrest();

		rlist = reverse<T>(*rlist);

		rlist->addtoback(node->data);		

		delete (node);

		return (rlist);
	}

}

If you encounter any problems or errors, please let me know by providing an example of the code, input, output, and an explanation. Thanks.

Share
Leave a comment

Example of Linked List

Example of Linked List

This code was compiled and tested on a Linux machine

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code is given ‘as is’. I do not take responsibilities of how they are used.

List.h:

#include <iostream>
using namespace std;

#ifndef LIST
#define LIST

typedef int ElementType;

class Node {
   public:

   // Create a linked list node by setting its data to the input parameter
   // and the next node in the linked list to NULL (0)
   Node(ElementType data_input);

   //The default constructor doesn't initialize the data members
   Node();

   // Contains the data of the linked list node
   ElementType data;	

   // Contains a pointer to the next item in the linked list
   Node *next;
};

class List
{
   private:

      // List class's private data member:
      Node *list_head;	// Contains a pointer to the first node in the
                        // linked list (the head of the list)

      int num_elements;

      // takes out the node with the smallest data member from this list,
      // and returns a pointer to it.
      Node *extractLargest(); 

   public:
      // Create a Linked list by initializing it's head to NULL (0)
      List();

      // Delete all the elements in the linked list when the list is deleted
      ~List();

      // Add a single element to the head of the linked list
      void insert(ElementType data_input);

      // Remove a single element from the head of the linked list
      void remove();	

      // Print all the elements in the linked list
      void show();

      // This function splits the list in half, adding the those half of
      // the elements with the largest values into a new linked list, and
      // keeping only those half of the elements with the smallest values
      // in the list on which this function is called. The function
      // returns a pointer to the new (heap allocated) list with the 
      // larger elements in it. If the original list contains an odd 
      // number of elements, then the returned list contains one
      // fewer element than the list on which this function is called.
      // If the original list is empty, the function returns a pointer
      // to a new empty List (not a NULL pointer).
      List *splitBigSmall();

      // This function splits the list in two, adding the the elements
      // with odd integer values into a new linked list, and keeping only
      // those elements with even integer values in the list on which
      // this function is called. The function returns a pointer to
      // the new (heap allocated) list with the odd elements in it. If the
      // original list is empty, or if there are no odd elements, the
      // function returns a pointer to a new empty List (not a NULL
      // pointer). 
      List *splitOddEven();
};

#endif

List.cpp:

#include 'List.h'

#include <string>

using namespace std;

// -------------------------------------
// ------------Node class---------------
// -------------------------------------

// 
// Create a linked list node by setting its data to the input parameter
// and the next node in the linked list to NULL (0)
Node::Node(ElementType data_input) {

    data = data_input;

    next = 0;

}

// Default constructor leaves data items unspecified
Node::Node() {
}

// -------------------------------------
// ------------List class---------------
// -------------------------------------

//
// Default constructor creates an empty list
//
List::List() {

    list_head = NULL;

    num_elements = 0;

}

//
// Delete all the elements in the linked list when the list is deleted
//
List::~List() {

    Node *next_node;

    Node *current_node = list_head;

    while (current_node != NULL) {

        next_node = current_node->next;

        delete(current_node);

        current_node = next_node;

    }	

}

//
// Add a single element to the head of the linked list
//
void List::insert(ElementType data_input) {

    Node *new_node = new Node(data_input);

	// If list_head == 0 then assign new_node as the list_head
	// else point new_node->next to list_head. After make that 
	// new node the list_head
    if (list_head == 0) {

        list_head = new_node;

    } else {

        new_node->next = list_head;

        list_head = new_node;	

    }

    num_elements++;

}

//
// Remove a single element from the head of the linked list
//
void List::remove() {

    if (list_head == NULL)
        return;	

	// Make new_head the node that is pointed by list_head->next
    Node *new_head = list_head->next;

	// Delete the node list_head 
    delete(list_head);

    //Make the new_head, the new list_head
    list_head = new_head;

    num_elements--;

}

//
// Print all the elements in the linked list
//
void List::show()
{

    cout << 'List of ' << num_elements << ' elements: ' ;

    Node *current_node = list_head;

    while (current_node != NULL) {

        cout << current_node->data << ' ';

        current_node = current_node->next;

    }

    cout << endl;
}

//
// splitOddEven()
//
List *List::splitOddEven()
{

	List *rlist = new List();

	if (num_elements > 0){

		Node *current_node = list_head;

		while (current_node != NULL){

			if (current_node->data % 2 == 1){

				rlist->insert(current_node->data);

				if (current_node == list_head){

					current_node = list_head->next;

					remove();

					current_node = current_node->next;

				}else{

					Node* previous_node = list_head;

					while (previous_node->next != current_node){
						previous_node = previous_node->next;
					}

					previous_node->next = current_node->next;

					// Delete the node list_head 
					Node *temp = current_node;
					current_node = current_node->next;
				    delete(temp);

					num_elements--;

				}

			}else{

				current_node = current_node->next;
			}
		}

	}
    return(rlist);

}

//
// extractLargest()
//
Node *List::extractLargest()
{

	Node *current_node = list_head;

	Node *largest_node = list_head;

	if (list_head != NULL){

		// Search Largest
		while(current_node != NULL ){

			if (largest_node->data < current_node->data){
				largest_node = current_node;
			}

			current_node = current_node->next;
		}

		current_node = largest_node;

		if (current_node == list_head){

			current_node = list_head->next;

			current_node = list_head;

			list_head = list_head->next;

		}else{

			Node* previous_node = list_head;

			while (previous_node->next != current_node){
				previous_node = previous_node->next;
			}

			previous_node->next = current_node->next;

		}

		//delete(current_node);

		num_elements--; 
	}

	return (largest_node); 
}

//
// splitBigSmall()
//
List *List::splitBigSmall()
{	
	List *rlist = new List();

	int numExtract;

	numExtract = num_elements / 2;

	if (num_elements > 0){

		Node *current_node = list_head;	

		//	2a. If original list have odd number of elements	
		//		then return list with larger elements in it, 
		//		should contain  one fewer element than 
		//		the list obj which this function is called.
		// 		This is already done by the division

		for (int i = 0; i < numExtract; i++){

			current_node = extractLargest();

			if (current_node != NULL)
				rlist->insert(current_node->data);

			//delete (current_node);
		}
	}

   return(rlist);

}

If you encounter any problems or errors, please let me know by providing an example of the code, input, output, and an explanation. Thanks.

Share
Leave a comment

Count all Alphabetics Characters Existent in the String

Process input file by Count all alphabetic characters existent in the string.

I would advice to compile them in Linux as I did.

NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code is given ‘as is’. I do not take responsibilities of how they are used.

StreamOperation.h:

#ifndef STREAM_OPERATION_H
#define STREAM_OPERATION_H

#include <iostream>		// for cout

#include <fstream>		// for ifstream, ofstream

#include <string>       // for String
#include <cctype>       // for classify and transform individual characters

using namespace std;

/**
 * author: Alejandro G. Carlstein
 * Class: StreamOperation
 * Description: This class will read a textfile and produce an output
 *				in another text file. The other text file will contain
 * 				a copy of the input file but all blank lines will be
 *				removed, the lines are going to be numbered, all
 *              semicolons will be replaces with the string 'SEMI-COLON',
 *				print the number of lines removed at the second to last
 *              line, and finally print the number of alphabetic characters
 */
class StreamOperation {

private:   

	bool doRemoveBlankLines;

	bool doReplaceAllStrings;

	bool doCountLines;	

	int numLinesRemoved;

	int numAlphaCharacters;

	string oldStr;

	string newStr;

	void replaceAll(string& str,
					string oldStr,
					string newStr);

	int countAlphaCharacters(string str);

	void copyStream(ifstream& fin,
			  		ofstream& fout);

public:

	// Default constructor
	StreamOperation(void);

	// * Get Methods *

	// Get the number of lines removed
	int getNumberLinesRemoved();

	// Get the number of alphabetic character
	int getNumberAlphaCharacters();

	// * Set Methods * 	

	// * Print Methods *

	// Print the number of blank lines removed
	void printNumberLinesRemoved(ofstream& output);		

	// Print the number of alphabetic characters
	void printNumberAlphaCharacters(ofstream& output);		

	// * Process Methods *

	// Copy the content from an input stream to an output stream
	void copy(ifstream& input,
			  ofstream& output);	

	// Copy the content from an input stream to an output stream.
    // This method can remove all the blank lines in the output
    // stream when copying.
	void copy(ifstream& input,
			  ofstream& output,
			  bool removeBlankLines);

	// Copy the content from an input stream to an output stream.
	// This method can remove all the blank lines in the output
 	// stream when copying.
	// This method can number all the lines in the output stream.
	void copy(ifstream& input,
			  ofstream& output,
			  bool removeBlankLines,
              bool numberLines);

	// Copy the content from an input stream to an output stream.
	// This method can replace all old strings for a new string
	// This method can remove all the blank lines in the output
 	// stream when copying.
	// This method can number all the lines in the output stream.
	void copy(ifstream& input,
			  ofstream& output,
              string oldString,
			  string newString,
			  bool removeBlankLines,
			  bool numberLines);

    // Default destructor
	~StreamOperation(void);
};

#endif

StreamOperation.cpp:

/**
 * author: Alejandro G. Carlstein  
 * Class: StreamOperation
 * Description: This class will read a textfile and produce an output
 *		in another text file. The other text file will contain
 * 		a copy of the input file but all blank lines will be
 *		removed, the lines are going to be numbered, all
 *              semicolons will be replaces with the string 'SEMI-COLON',
 *		print the number of lines removed at the second to last
 *              line, and finally print the number of alphabetic characters
 */

#include 'StreamOperation.h'

/**
 * Public Methods
 */

/**
 * StreamOperation
 * @description: Default Constructor
 */
StreamOperation::StreamOperation(void){

	numLinesRemoved = 0;

	numAlphaCharacters = 0;

	doRemoveBlankLines = false;

	doReplaceAllStrings = false;

	doCountLines = false;

	oldStr = '';

	newStr = '';

}

// * Get Methods *

/**
 * getNumberLinesRemoved
 * @description: Get the number of lines removed
 * @return: integer
*/
int StreamOperation::getNumberLinesRemoved(){
	return numLinesRemoved;
}

/**
 * getNumberAlphaCharacters
 * @description: Get the number of alphabetic character
 * @return: integer
 */
int StreamOperation::getNumberAlphaCharacters(){
	return numAlphaCharacters;
}

// * Set Methods *

// * Print Methods *

// Print the number of blank lines removed
void StreamOperation:RazzrintNumberLinesRemoved(ofstream& output){
	if (output.is_open()){
		output << numLinesRemoved;
	} else {
			cerr << '[X] Error: Program cannot write file!' << endl
				 << 'Exit program!' << endl;
	}
}

// Print the number of alphabetic characters
void StreamOperation:RazzrintNumberAlphaCharacters(ofstream& output){
	if (output.is_open()){
		output << numAlphaCharacters;
	} else {
			cerr << '[X] Error: Program cannot write file!' << endl
				 << 'Exit program!' << endl;
	}
}

// * Process Methods *

/**
 * copy
 * @description: Copy the content from an input stream to an output stream
 * @param: input, output
 */
void StreamOperation::copy(ifstream& input,
						   ofstream& output){

	doRemoveBlankLines = false;

	doReplaceAllStrings = false;

	doCountLines = false;

	copyStream(input, output);

}

/**
 * copy
 * @description: Copy the content from an input stream to an output stream.
 *               This method can remove all the blank lines in the output
 *				 stream when copying.
 *
 * @param: input, output, removeBlankLines
 */
void StreamOperation::copy(ifstream& input,
						   ofstream& output,
						   bool removeBlankLines){

	doReplaceAllStrings = false;

	doCountLines = false;

	doRemoveBlankLines = removeBlankLines;

	copyStream(input, output);

}

/**
 * copy
 * @description: Copy the content from an input stream to an output stream.
 *               This method can remove all the blank lines in the output
 *				 stream when copying.
 *               This method can number all the lines in the output stream.
 * @param: input, output, removeBlankLines, numberLines
 */
void StreamOperation::copy(ifstream& input,
						   ofstream& output,
						   bool removeBlankLines,
						   bool numberLines){

	doReplaceAllStrings = false;

	doCountLines = numberLines;

	doRemoveBlankLines = removeBlankLines;

	copyStream(input, output);

}

/**
 * copy
 * @description: Copy the content from an input stream to an output stream.
 *				 This method can replace all old strings for a new string
 *               This method can remove all the blank lines in the output
 *				 stream when copying.
 *               This method can number all the lines in the output stream.
 * @param: input, output, oldstring, new string, removeBlankLines, numberLines
 */
void StreamOperation::copy(ifstream& input,
			  			   ofstream& output,
			               string oldString,
			 			   string newString,
			  			   bool removeBlankLines,
						   bool numberLines){

	doReplaceAllStrings = true;

	oldStr = oldString;

	newStr = newString;

	doCountLines = numberLines;

	doRemoveBlankLines = removeBlankLines;

	copyStream(input, output);

}

/**
 * StreamOperation
 * @description: Default Destructor
 */
StreamOperation::~StreamOperation(void){
};

/**
 * Private Methods
 */

/**
 * replaceAll
 * @description: This method will remove all substrings for a new substring
 *               inside the string
 * @param: str, oldStr, newStr
 */
void StreamOperation::replaceAll(string& str,
			   		  			 string oldStr,
				  	  			 string newStr){

	// The method find return the unsigned int string::npos
    // if substring not found. Therefore, string::size_type
	// type is used
	string::size_type position = 0;

	// Until the end of the string is reached, search for every
    // string that maches the old string and replace it with
	// the new string.
	while((position = str.find(oldStr, position)) != string::npos){
		str.replace(position,
					oldStr.length(),
					newStr);
		position++;
	}
}

/**
 * countAlphaCharacters
 * @description: Count all alphabetics characters existent in the string
 * @param: str
 * @return: integer
 */
int StreamOperation::countAlphaCharacters(string str){

	int countAlpha = 0;

	// Go thought the whole string, counting all
	// the alphabetic characters
	for (int position = 0;
		 position < str.length();
		 position++){

		countAlpha += (isalpha(str[position]) ? 1 : 0);

	}

	return countAlpha;
}

/**
 * copyStream
 * @description: This method copy the content from an input stream to
 *               an output stream.
 *				 Base on the flags doRemoveBlankLines, doCountLines, and
 *               doReplaceAllStrings:
 *				 This method can replace all old strings for a new string
 *               This method can remove all the blank lines in the output
 *				 stream when copying.
 *               This method can number all the lines in the output stream.
 * @param: fin, fout
 */
void StreamOperation::copyStream(ifstream& fin,
							     ofstream& fout){
	int lineCounter;

	string strBuffer;

	numLinesRemoved = 0;

	numAlphaCharacters = 0;	

	lineCounter = 1;

	// Check if input and output stream can be open
	if (fin.is_open()){

		if (fout.is_open()){	

			//Read one line at the time as a string until eof
			while(!fin.eof()){

				getline(fin, strBuffer);

				// If the string is empty and doRemoveBlankLines
				// is true, count the string as as a blank line
				// else process the string
				if (strBuffer.empty() && doRemoveBlankLines){

					numLinesRemoved++;

				}else{

					// Count the alphabetic character of the string
					numAlphaCharacters += countAlphaCharacters(strBuffer);

					// Replace all semicolons with the string SEMICOLON
					if (doReplaceAllStrings)
						replaceAll(strBuffer, oldStr, newStr);

					// Add a number to each line if doCountLines is true
					if (doCountLines)
						fout << lineCounter++ << ' ';					

					fout << strBuffer << endl;

				}

			}

		} else {
			cerr << '[X] Error: Program cannot write file!' << endl
				 << 'Exit program!' << endl;
		}

	}else{
		cerr << '[X] Error: Program cannot read file!' << endl
			 << 'Exit Program!' << endl;
	}

}

processFile.cpp:

/**
 * Author: Alejandro G. Carlstein
 * Description: Use the file StreamOperations.cpp as an input file
 *				and process it using StreamOperation class
 */

#include <iostream>
#include <fstream>
#include 'StreamOperation.h'

static const string INPUT_FILE = 'StreamOperation.cpp';
static const string OUTPUT_FILE = 'Output.txt';
static const string SEMI_COLON = ';';
static const string STR_SEMI_COLON = 'SEMI-COLON';

/**
 * Main function
 * @param: argc, argv
 */

int main(int argc, char *argv[]){

	ifstream inputFile;
	ofstream outputFile;

	// If the program is executed with two parameters (file 1  and file 2)
    // used these parameters as input file and output file
	// If the program is executed without parameters use default files
    // If the program is executed with the -h parameter display help
	// If the program get more than two parameters or
    // wrong key display help
	if (argc == 1 || argc == 3){

		if (argc == 1){

			inputFile.open(INPUT_FILE.data());

			outputFile.open(OUTPUT_FILE.data());	

		}else{

			inputFile.open(argv[1]);

			outputFile.open(argv[2]);
		}

		StreamOperation StrOp;

		// Copy the content from the input file to the output file
	    // In the process, replace the ; with string SEMI-COLON,
		// remove the blank lines and number all the lines
		StrOp.copy(inputFile,
				   outputFile,
				   SEMI_COLON,
				   STR_SEMI_COLON,
				   true,
	               true);

		outputFile << 'Lines Removed: '
				   << StrOp.getNumberLinesRemoved() << endl;

		outputFile << 'Alphabetic Characters: '
				   << StrOp.getNumberAlphaCharacters();

		inputFile.close();

		outputFile.close();

	} else {
		cout << argv[0] << ' input_file output_file ' << endl;
	}	

	return 0;
}

input.txt:

23
This is
An example

of things;
That we can input;

;; aaa ;

output.txt:

1 23
2 This is
3 An example
4 of thingsSEMI-COLON
5 That we can inputSEMI-COLON
6 SEMI-COLONSEMI-COLON aaa SEMI-COLON

If you encounter any problems or errors, please let me know by providing an example of the code, input, output, and an explanation. Thanks.

/**
* author: Alejandro G. Carlstein
* Course: CS 240
* Class: StreamOperation
* Description: This class will read a textfile and produce an output
*        in another text file. The other text file will contain
*         a copy of the input file but all blank lines will be
*        removed, the lines are going to be numbered, all
*              semicolons will be replaces with the string ‘SEMI-COLON’,
*        print the number of lines removed at the second to last
*              line, and finally print the number of alphabetic characters
*/

#include “StreamOperation.h”

/**
* Public Methods
*/

/**
* StreamOperation
* @description: Default Constructor
*/
StreamOperation::StreamOperation(void){

numLinesRemoved = 0;

numAlphaCharacters = 0;

doRemoveBlankLines = false;

doReplaceAllStrings = false;

doCountLines = false;

oldStr = “”;

newStr = “”;

}

// * Get Methods *

/**
* getNumberLinesRemoved
* @description: Get the number of lines removed
* @return: integer
*/
int StreamOperation::getNumberLinesRemoved(){
return numLinesRemoved;
}

/**
* getNumberAlphaCharacters
* @description: Get the number of alphabetic character
* @return: integer
*/
int StreamOperation::getNumberAlphaCharacters(){
return numAlphaCharacters;
}

// * Set Methods *

// * Print Methods *

// Print the number of blank lines removed
void StreamOperation:RazzrintNumberLinesRemoved(ofstream& output){
if (output.is_open()){
output << numLinesRemoved;
} else {
cerr << “[X] Error: Program cannot write file!” << endl
<< “Exit program!” << endl;
}
}

// Print the number of alphabetic characters
void StreamOperation:RazzrintNumberAlphaCharacters(ofstream& output){
if (output.is_open()){
output << numAlphaCharacters;
} else {
cerr << “[X] Error: Program cannot write file!” << endl
<< “Exit program!” << endl;
}
}

// * Process Methods *

/**
* copy
* @description: Copy the content from an input stream to an output stream
* @param: input, output
*/
void StreamOperation::copy(ifstream& input,
ofstream& output){

doRemoveBlankLines = false;

doReplaceAllStrings = false;

doCountLines = false;

copyStream(input, output);

}

/**
* copy
* @description: Copy the content from an input stream to an output stream.
*               This method can remove all the blank lines in the output
*                 stream when copying.
*
* @param: input, output, removeBlankLines
*/
void StreamOperation::copy(ifstream& input,
ofstream& output,
bool removeBlankLines){

doReplaceAllStrings = false;

doCountLines = false;

doRemoveBlankLines = removeBlankLines;

copyStream(input, output);

}

/**
* copy
* @description: Copy the content from an input stream to an output stream.
*               This method can remove all the blank lines in the output
*                 stream when copying.
*               This method can number all the lines in the output stream.
* @param: input, output, removeBlankLines, numberLines
*/
void StreamOperation::copy(ifstream& input,
ofstream& output,
bool removeBlankLines,
bool numberLines){

doReplaceAllStrings = false;

doCountLines = numberLines;

doRemoveBlankLines = removeBlankLines;

copyStream(input, output);

}

/**
* copy
* @description: Copy the content from an input stream to an output stream.
*                 This method can replace all old strings for a new string
*               This method can remove all the blank lines in the output
*                 stream when copying.
*               This method can number all the lines in the output stream.
* @param: input, output, oldstring, new string, removeBlankLines, numberLines
*/
void StreamOperation::copy(ifstream& input,
ofstream& output,
string oldString,
string newString,
bool removeBlankLines,
bool numberLines){

doReplaceAllStrings = true;

oldStr = oldString;

newStr = newString;

doCountLines = numberLines;

doRemoveBlankLines = removeBlankLines;

copyStream(input, output);

}

/**
* StreamOperation
* @description: Default Destructor
*/
StreamOperation::~StreamOperation(void){
};

/**
* Private Methods
*/

/**
* replaceAll
* @description: This method will remove all substrings for a new substring
*               inside the string
* @param: str, oldStr, newStr
*/
void StreamOperation::replaceAll(string& str,
string oldStr,
string newStr){

// The method find return the unsigned int string::npos
// if substring not found. Therefore, string::size_type
// type is used
string::size_type position = 0;

// Until the end of the string is reached, search for every
// string that maches the old string and replace it with
// the new string.
while((position = str.find(oldStr, position)) != string::npos){
str.replace(position,
oldStr.length(),
newStr);
position++;
}
}

/**
* countAlphaCharacters
* @description: Count all alphabetics characters existent in the string
* @param: str
* @return: integer
*/
int StreamOperation::countAlphaCharacters(string str){

int countAlpha = 0;

// Go thought the whole string, counting all
// the alphabetic characters
for (int position = 0;
position < str.length();
position++){

countAlpha += (isalpha(str[position]) ? 1 : 0);

}

return countAlpha;
}

/**
* copyStream
* @description: This method copy the content from an input stream to
*               an output stream.
*                 Base on the flags doRemoveBlankLines, doCountLines, and
*               doReplaceAllStrings:
*                 This method can replace all old strings for a new string
*               This method can remove all the blank lines in the output
*                 stream when copying.
*               This method can number all the lines in the output stream.
* @param: fin, fout
*/
void StreamOperation::copyStream(ifstream& fin,
ofstream& fout){
int lineCounter;

string strBuffer;

numLinesRemoved = 0;

numAlphaCharacters = 0;

lineCounter = 1;

// Check if input and output stream can be open
if (fin.is_open()){

if (fout.is_open()){

//Read one line at the time as a string until eof
while(!fin.eof()){

getline(fin, strBuffer);

// If the string is empty and doRemoveBlankLines
// is true, count the string as as a blank line
// else process the string
if (strBuffer.empty() && doRemoveBlankLines){

numLinesRemoved++;

}else{

// Count the alphabetic character of the string
numAlphaCharacters += countAlphaCharacters(strBuffer);

// Replace all semicolons with the string SEMICOLON
if (doReplaceAllStrings)
replaceAll(strBuffer, oldStr, newStr);

// Add a number to each line if doCountLines is true
if (doCountLines)
fout << lineCounter++ << ” “;

fout << strBuffer << endl;

}

}

} else {
cerr << “[X] Error: Program cannot write file!” << endl
<< “Exit program!” << endl;
}

}else{
cerr << “[X] Error: Program cannot read file!” << endl
<< “Exit Program!” << endl;
}

}

/**
 * author: Alejandro G. Carlstein
 * Course: CS 240
 * Class: StreamOperation
 * Description: This class will read a textfile and produce an output
 *		in another text file. The other text file will contain
 * 		a copy of the input file but all blank lines will be
 *		removed, the lines are going to be numbered, all
 *              semicolons will be replaces with the string 'SEMI-COLON',
 *		print the number of lines removed at the second to last
 *              line, and finally print the number of alphabetic characters
 */

#include 'StreamOperation.h'

/**
 * Public Methods
 */

/**
 * StreamOperation
 * @description: Default Constructor
 */
StreamOperation::StreamOperation(void){

	numLinesRemoved = 0;

	numAlphaCharacters = 0;

	doRemoveBlankLines = false;

	doReplaceAllStrings = false;

	doCountLines = false;

	oldStr = '';

	newStr = '';

}

// * Get Methods *

/**
 * getNumberLinesRemoved
 * @description: Get the number of lines removed
 * @return: integer
*/
int StreamOperation::getNumberLinesRemoved(){
	return numLinesRemoved;
}

/**
 * getNumberAlphaCharacters
 * @description: Get the number of alphabetic character
 * @return: integer
 */
int StreamOperation::getNumberAlphaCharacters(){
	return numAlphaCharacters;
}

// * Set Methods *

// * Print Methods *

// Print the number of blank lines removed
void StreamOperation:RazzrintNumberLinesRemoved(ofstream& output){
	if (output.is_open()){
		output << numLinesRemoved;
	} else {
			cerr << '[X] Error: Program cannot write file!' << endl
				 << 'Exit program!' << endl;
	}
}

// Print the number of alphabetic characters
void StreamOperation:RazzrintNumberAlphaCharacters(ofstream& output){
	if (output.is_open()){
		output << numAlphaCharacters;
	} else {
			cerr << '[X] Error: Program cannot write file!' << endl
				 << 'Exit program!' << endl;
	}
}

// * Process Methods *

/**
 * copy
 * @description: Copy the content from an input stream to an output stream
 * @param: input, output
 */
void StreamOperation::copy(ifstream& input,
						   ofstream& output){

	doRemoveBlankLines = false;

	doReplaceAllStrings = false;

	doCountLines = false;

	copyStream(input, output);

}

/**
 * copy
 * @description: Copy the content from an input stream to an output stream.
 *               This method can remove all the blank lines in the output
 *				 stream when copying.
 *
 * @param: input, output, removeBlankLines
 */
void StreamOperation::copy(ifstream& input,
						   ofstream& output,
						   bool removeBlankLines){

	doReplaceAllStrings = false;

	doCountLines = false;

	doRemoveBlankLines = removeBlankLines;

	copyStream(input, output);

}

/**
 * copy
 * @description: Copy the content from an input stream to an output stream.
 *               This method can remove all the blank lines in the output
 *				 stream when copying.
 *               This method can number all the lines in the output stream.
 * @param: input, output, removeBlankLines, numberLines
 */
void StreamOperation::copy(ifstream& input,
						   ofstream& output,
						   bool removeBlankLines,
						   bool numberLines){

	doReplaceAllStrings = false;

	doCountLines = numberLines;

	doRemoveBlankLines = removeBlankLines;

	copyStream(input, output);

}

/**
 * copy
 * @description: Copy the content from an input stream to an output stream.
 *				 This method can replace all old strings for a new string
 *               This method can remove all the blank lines in the output
 *				 stream when copying.
 *               This method can number all the lines in the output stream.
 * @param: input, output, oldstring, new string, removeBlankLines, numberLines
 */
void StreamOperation::copy(ifstream& input,
			  			   ofstream& output,
			               string oldString,
			 			   string newString,
			  			   bool removeBlankLines,
						   bool numberLines){

	doReplaceAllStrings = true;

	oldStr = oldString;

	newStr = newString;

	doCountLines = numberLines;

	doRemoveBlankLines = removeBlankLines;

	copyStream(input, output);

}

/**
 * StreamOperation
 * @description: Default Destructor
 */
StreamOperation::~StreamOperation(void){
};

/**
 * Private Methods
 */

/**
 * replaceAll
 * @description: This method will remove all substrings for a new substring
 *               inside the string
 * @param: str, oldStr, newStr
 */
void StreamOperation::replaceAll(string& str,
			   		  			 string oldStr,
				  	  			 string newStr){

	// The method find return the unsigned int string::npos
    // if substring not found. Therefore, string::size_type
	// type is used
	string::size_type position = 0;

	// Until the end of the string is reached, search for every
    // string that maches the old string and replace it with
	// the new string.
	while((position = str.find(oldStr, position)) != string::npos){
		str.replace(position,
					oldStr.length(),
					newStr);
		position++;
	}
}

/**
 * countAlphaCharacters
 * @description: Count all alphabetics characters existent in the string
 * @param: str
 * @return: integer
 */
int StreamOperation::countAlphaCharacters(string str){

	int countAlpha = 0;

	// Go thought the whole string, counting all
	// the alphabetic characters
	for (int position = 0;
		 position < str.length();
		 position++){

		countAlpha += (isalpha(str[position]) ? 1 : 0);

	}

	return countAlpha;
}

/**
 * copyStream
 * @description: This method copy the content from an input stream to
 *               an output stream.
 *				 Base on the flags doRemoveBlankLines, doCountLines, and
 *               doReplaceAllStrings:
 *				 This method can replace all old strings for a new string
 *               This method can remove all the blank lines in the output
 *				 stream when copying.
 *               This method can number all the lines in the output stream.
 * @param: fin, fout
 */
void StreamOperation::copyStream(ifstream& fin,
							     ofstream& fout){
	int lineCounter;

	string strBuffer;

	numLinesRemoved = 0;

	numAlphaCharacters = 0;	

	lineCounter = 1;

	// Check if input and output stream can be open
	if (fin.is_open()){

		if (fout.is_open()){	

			//Read one line at the time as a string until eof
			while(!fin.eof()){

				getline(fin, strBuffer);

				// If the string is empty and doRemoveBlankLines
				// is true, count the string as as a blank line
				// else process the string
				if (strBuffer.empty() && doRemoveBlankLines){

					numLinesRemoved++;

				}else{

					// Count the alphabetic character of the string
					numAlphaCharacters += countAlphaCharacters(strBuffer);

					// Replace all semicolons with the string SEMICOLON
					if (doReplaceAllStrings)
						replaceAll(strBuffer, oldStr, newStr);

					// Add a number to each line if doCountLines is true
					if (doCountLines)
						fout << lineCounter++ << ' ';					

					fout << strBuffer << endl;

				}

			}

		} else {
			cerr << '[X] Error: Program cannot write file!' << endl
				 << 'Exit program!' << endl;
		}

	}else{
		cerr << '[X] Error: Program cannot read file!' << endl
			 << 'Exit Program!' << endl;
	}

}
Share
Leave a comment

Code Examples in C++

Here are some code examples written in C++
Even do they are written in C++, I would advice to compile them in Linux as I did. If you encounter any problems or errors, please let me know by providing an example of the code, input, output, and an explanation. Thanks
NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. I do not take responsibilities of how they are used.

Share
Leave a comment