Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Linked List, binary file, and sorting.

DJNixyDJNixy Posts: 1Member
Hi,

i'm having trouble with my assignment:

1. Create the unsorted binary file from the text file (DONE)
2. Generate a linked list index for the binary file, with ID as key (DONE)
3. Display the contents of the binary file in sorted order. (Problem)

I'm using Microsoft Visual C++ express edition 2005.

[b]supermarket.h[/b]
[code]
//****************************************************************
// Programmer: Niki Akbar Djayasaputra
// Date: 25 October 2008
// Software: Microsoft Visual C++ 2005 Express Edition
// Platform: Microsoft Windows XP Professional SP2
// Purpose: Header file for operations on a linked list.
//
//****************************************************************

//#ifndef SUPERMARKET_H
//#define SUPERMARKET_H
#include
using std::cout;
using std::endl;

#include
using std::string;

class Supermarket
{
public:
//default Supermarket constructor
Supermarket( int = 0, string = "", int = 0, float = 0.00 );

//accessor functions
void setID( int );
int getID() const;

void setItemName( string );
string getItemName() const;

void setStock( int );
int getStock() const;

void setAveragePrice( float );
float getAveragePrice() const;



private:
int id;
char itemName[13];
int stock;
float averagePrice;

}; //end class Supermarket

//////////////////////////////////////////////////////////////////
class Node
{
public:
int id; // Data field
long rec_no; // Data field
Node *pNext; // Pointer field - to next node
//-------------------------------------------------------------
Node(int this_id, long this_recnum) // Constructor
{
id = this_id;
rec_no = this_recnum;
pNext = NULL;
}
//-------------------------------------------------------------
void DisplayNode() // Display this node
{
cout << id << " " << rec_no << endl;
}
}; //end class Node
////////////////////////////////////////////////////////////////
class SortedList
{
private:
Node *pHead; // Pointer to first node

public:
//-------------------------------------------------------------
SortedList() // Constructor
{
pHead = NULL;
}
//-------------------------------------------------------------
void Insert(int key, long recnum) // Insert node in order
{
Node *pNewNode = new Node(key, recnum); // Make new node
Node *pPrevious = NULL;
Node *pCurrent = pHead; // Start at first node (Head)

while (pCurrent != NULL && key > pCurrent->id)
{ //continue until end of list or until current node > key
pPrevious = pCurrent;
pCurrent = pCurrent->pNext; // Go to next node
}

if (pPrevious==NULL) // At beginning of list
pHead = pNewNode; // Head points to new node
else // ...not at beginning
pPrevious->pNext = pNewNode; // Previous node points to new node

pNewNode->pNext = pCurrent; // New node points to current node
} //end insert()
//-------------------------------------------------------------
void DisplayList() // Displays contents of list
{ // (use this to check sorted list)
Node *pCurrent = pHead; // Start at beginning of list
cout << "List contents (first node to last node): "<<endl;

while(pCurrent != NULL) // While not end of list,
{
pCurrent->DisplayNode(); // Display data in this node
pCurrent = pCurrent->pNext; // Move to next node
}
cout << "Press any key to continue...";
getchar();
cout<<endl;
} //end DisplayList
//-------------------------------------------------------------
Node* Find(int key) // Find a key field in the list
{ // (return pointer to that node)
Node *pCurrent = pHead; // Start at the first node
while (pCurrent->id != key) // ...while not a match
{
if (pCurrent->pNext == NULL) // If at end of list...
return NULL; // ...key not found
else
pCurrent = pCurrent->pNext;// Move to next node
}
return pCurrent; // We have found it...
} // End method Find()

}; //end class SortedList

[/code]

[b]supermarket.cpp[/b]
[code]
//****************************************************************
// Programmer: Niki Akbar Djayasaputra
// Date: 25 October 2008
// Software: Microsoft Visual C++ 2005 Express Edition
// Platform: Microsoft Windows XP Professional SP2
// Purpose: Accessor functions for item information in class
//****************************************************************

#include
using std::string;

#include "Supermarket.h"

//default Supermarket constructor
Supermarket::Supermarket( int IDValue, string itemNameValue, int stockValue, float averagePriceValue )
{
setID( IDValue );
setItemName( itemNameValue );
setStock( stockValue );
setAveragePrice( averagePriceValue );
}

int Supermarket::getID() const
{
return id;
}

void Supermarket::setID( int IDValue )
{
id = IDValue;
}

string Supermarket::getItemName() const
{
return itemName;
}

void Supermarket::setItemName( string itemNameString )
{
const char *itemNameValue = itemNameString.data();
int length = itemNameString.size();
length = (length < 15 ? length : 14);
strncpy( itemName, itemNameValue, length);
itemName[ length ] = ''; //append null character to itemName

}


int Supermarket::getStock() const
{
return stock;
}

void Supermarket::setStock( int stockValue)
{
stock = stockValue;
}

float Supermarket::getAveragePrice() const
{
return averagePrice;
}

void Supermarket::setAveragePrice( float averagePriceValue)
{
averagePrice = averagePriceValue;
}
[/code]

[b]main.cpp[/b]
[code]//****************************************************************
// Programmer: Niki Akbar Djayasaputra
// Date: 25 October 2008
// Software: Microsoft Visual C++ 2005 Express Edition
// Platform: Microsoft Windows XP Professional SP2
// Purpose: Assignment using a binary file
//****************************************************************

#include
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::fixed;
using std::ios;
using std::left;
using std::right;
using std::showpoint;

#include //file stream
using std::ifstream; //input file stream
using std::ofstream; //output file stream
using std::fstream;
using std::ostream;

#include
using std::setw;
using std::setprecision;

#include
using std::string;

#include
using std::exit; //exit function prototype

#include "supermarket.h"

int enterChoice();
void displayAllData( fstream& );
void countTotalStock( fstream& );
void countTotalValue( fstream& );

void editPrice( fstream& );

void outputLine( ostream&, const Supermarket &);
int Get_Data();

enum Choices { DISPLAY = 1, TOTALSTOCK, TOTALPRICE, EDITPRICE, END };

int main()
{
int id;
char itemName[13];
int stock;
float averagePrice;

int id_search; // ID to search for in list
long count; // Counter for record number
Node *found; // Pointer for return from Find method


int choice; //store user choice

Supermarket market; //create record
SortedList MySortedList; // Initialise new list (it calls constructor)

//ifstream constructor opens the file
ifstream inSupermarketFile( "AOOP_Assig.txt", ios::in);

//exit program if ifstream could not open the file
if (!inSupermarketFile)
{
cerr << "File could not be opened, press enter to exit" << endl;
getchar();

exit(1);
}

//creating a random access file
ofstream outBinaryFile("AOOP_Assig.dat", ios::out | ios::binary );

//exit program if fstream could not create file
if (!outBinaryFile)
{
cerr <<"File could not be created" << endl;
exit(1);
}
else
{
cout << "File created" << endl;
}

fstream binaryFile("AOOP_Assig.dat", ios::in | ios::out | ios::binary );

//exit program if fstream could not create file
if (!binaryFile)
{
cerr <<"binaryFile could not be opened" << endl;
exit(1);
}
else
{
cout << "fstream binaryFile; is working" << endl;
}


//Supermarket blankClient; // constructor zeros out each data member

////output 100 blank records to file
//for( int i = 0; i < 100; i++)
//{
//binaryFile.write( reinterpret_cast< const char * >( &blankClient ), sizeof(Supermarket));
//}


//Writing item list to binary file

inSupermarketFile >> id >> itemName >> stock >> averagePrice; //Priming read

//read the files then write them into binary file UNSORTED

while(!inSupermarketFile.eof() )
{
market.setID(id);
market.setItemName(itemName);
market.setStock(stock);
market.setAveragePrice(averagePrice);

//write user-specified information in file
binaryFile.write( reinterpret_cast< const char * >(&market), sizeof(Supermarket));
inSupermarketFile >> id >> itemName >> stock >> averagePrice;


}


//binaryFile.close();

//binaryFile.clear(); //to the first line in binary file
binaryFile.seekg( 0 ); //to the first line in binary file
//Inserting into linked list

//read first line
binaryFile.read(reinterpret_cast(&market), sizeof(Supermarket));

count = 0;

while (!binaryFile.eof())
{
MySortedList.Insert(market.getID(), count); // Insert ID, record number to node in the list

count++; // Increment record number counter
binaryFile.read(reinterpret_cast(&market), sizeof(Supermarket));

}

binaryFile.clear() ;

//Menus
while (( choice = enterChoice() ) != END )
{

switch( choice)
{
case DISPLAY: //display the contents of the binary file in sorted order
displayAllData( binaryFile);
break;

case TOTALSTOCK: //calculate the total number of all the items in stock.
countTotalStock( binaryFile );
break;
case TOTALPRICE: //calculate the total value of all items in stock based on the average price of each item
countTotalValue( binaryFile );
break;
case EDITPRICE: //edit the price for any requested item based on ITEM ID
editPrice( binaryFile );
break;
default: //display error if user does not select valid choice
cerr << "Incorrect choice" << endl;
break;
}

binaryFile.clear(); //reset end-of-file indicator
}

getchar();
return 0;
}


//-------------------------------------------------------------------
int Get_Data()
{
int value;

cout<<"Key in a number: ";
cin>>value;

return value;
} // End function GetData()
//-------------------------------------------------------------------

int enterChoice()
{
//display available options
cout << "
Enter your choice" << endl
<< "1 - Display the contents of the binary file" << endl
<< "2 - Calculate the total number of all items in stock" << endl
<< "3 - Calculate the total value of all items in stock" << endl
<< "4 - Edit the price" << endl
<< "5 - End Program
? " ;

int menuChoice;
cin >> menuChoice; //input menu selection from user
return menuChoice;
}

void displayAllData( fstream &readFromFile)
{

Supermarket marketRead;

cout << setw( 2 ) << "
ID" << setw( 11 ) << "Item Name" << setw( 14 ) << "Stock" << setw( 17 ) << "Average Price" << endl;

readFromFile.seekg(0); //set the pointer to the first record
//read first record from file
readFromFile.read( reinterpret_cast< char * >( &marketRead ), sizeof(Supermarket) );

while ( !readFromFile.eof() )
{

//display data
if ( marketRead.getID() > 0)
{
outputLine( cout , marketRead );

}
readFromFile.read( reinterpret_cast< char * >( &marketRead ), sizeof(Supermarket) );
}

readFromFile.clear();


}

void countTotalStock( fstream &readFile )
{
int totalStock = 0;

//put pointer to the beginning of file
readFile.seekg(0);

//read first record from file
Supermarket readMarket;

readFile.read( reinterpret_cast< char * >( &readMarket ), sizeof( Supermarket) );


while( !readFile.eof())
{
//accumulate the stocks
totalStock +=readMarket.getStock();

//read next record
readFile.read( reinterpret_cast< char * >( &readMarket ), sizeof( Supermarket) );
}

cout << "
Total items: " << totalStock << endl;
readFile.clear();
}

void countTotalValue( fstream &readFile )
{
float totalValue = 0; //accumulated total value after price * stock
float totalPerItem = 0; //total per item price * stock

readFile.seekg(0);
//read first record from file

Supermarket readMarket;

readFile.read( reinterpret_cast< char * >( &readMarket ), sizeof( Supermarket) );

while( !readFile.eof())
{
totalPerItem = readMarket.getStock() * readMarket.getAveragePrice();
//update record price

totalValue +=totalPerItem;

readFile.read( reinterpret_cast< char * >( &readMarket ), sizeof( Supermarket) );
}

cout << "
Total value of all the items in stock: " << totalValue << endl;
readFile.clear();
}

void editPrice( fstream &updateFile )
{
int id;
cout << "Enter item id to update:
>";
cin >> id;

updateFile.seekg( ( id - 1 ) * sizeof( Supermarket ));

//read first record from file
Supermarket editMarket;
updateFile.read( reinterpret_cast< char * >( &editMarket ), sizeof( Supermarket) );

//update record
if ( editMarket.getID() != 0)
{
outputLine( cout, editMarket ); //display the record

//request user to specify price
cout << "
Enter new price: ";
float newPrice;
cin >> newPrice;

//update record price
editMarket.setAveragePrice( newPrice);
outputLine( cout, editMarket ); //display the record

//move file-position pointer to correct record in file
updateFile.seekp( ( id - 1) * sizeof( Supermarket ));

//write updated record over old record in file
updateFile.write( reinterpret_cast< const char * >( &editMarket), sizeof(Supermarket));
}
else //display error if account does not exist
{
cerr << "ID #" << id << " was not found." << endl;
}
}


void outputLine( ostream &output, const Supermarket &record )
{

output << left << setw( 4 ) << record.getID()
<< setw( 16)<< record.getItemName()
<< setw( 6 ) << right << record.getStock()
<< setw( 10) << setprecision( 2) << fixed << showpoint << record.getAveragePrice() << endl;

}
[/code]

I don't know how to display all data in binary file, using linked list, show them in sorted order.


I need help and suggestion please.
Thanks.
Sign In or Register to comment.