Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Displaying the name of the new record (linked list)

I can compile the following code, but, when i press 'i' for insertion of a new record and i type the charcaters, the screen shows a strange charcacters, but correct position. Please help!!!

From Main.cpp
#include <iostream>
#include "Database.h"
#include <string>
using namespace std;
int main()
{
Database db;
db.create(5);
db.display();
char choice;
do
{
cout << "(i) insert\n";
cout << "(r) remove\n";
cout << "(d) display\n";
cout << "(q) quit\n";
cout << ".........Input?";
cin >> choice;
cout << endl;
switch (choice)
{
case 'i': case 'I':
{
char name1[6];
int pos1;
Record *r = new Record;
cout << "Name of Record? ";
cin >> name1;
cout << "Insert before Record#? ";
cin >> pos1;
char *NameInHeap = new char[6];
NameInHeap[0] = '\0';
strcpy(NameInHeap, name1);
r->setName(NameInHeap);
db.insert(pos1, r);
}
break;

From Database.cpp (from database.h -class)
#include <iostream>
#include "Database.h"
#include <time.h>
#include <string>
using namespace std;
Database::Database()
{
srand((unsigned int) time(NULL));
numRecord = 0;
pFirst = 0;
}
Database::~Database()
{;}
void Database::create(int n)
{
numRecord = n;
Record *pH, *pT, *pL;
int i;
pH = new Record;
pL = pH;
pL->setName(genName());
for (i=1; i<n; i++)
{
pT = new Record;
pL->setNext(pT);
pL = pT;
pL->setName(genName());
}
pFirst = pH;
}
char* Database::genName()
{
char ch;
char* tempName = new char[5];
tempName[0] = '\0';
for (int i=0; i<5; i++)
{
ch = (char) ((rand()%26) + 97);
tempName [i] = ch;
}
return tempName;
}
void Database::display()
{
if (pFirst!=0)
{
Record *pTemp = pFirst;
int i=0;
do
{
cout << "Record #" << i << ": " << pTemp->getName() << endl;
pTemp = pTemp->getNext();
i++;
}
while (pTemp!=0);
}
}
bool Database::remove(char *recName)
{
Record *pCurr, *pPrev, *rec;
pCurr = pFirst;
int i = 0;
do
{
pPrev = pCurr;
pCurr = pPrev->getNext();
i++;
}
while(pCurr!=0);
rec = pCurr->getNext();
pPrev->setNext(rec);
delete pCurr;
return true;
}
bool Database::insert(int pos, Record *rec)
{
Record *pC;
pC = pFirst;
int i = 5;
if(pos>= numRecord)
{
cout << "Cannot insert!!!\n";
}
else
{
while (i>pos)
{
pC = pC->getNext();
i--;
}
rec = new Record;
rec->setNext(pC->getNext());
pC->setNext(rec);
}
return false;
}

thank you very much!!!
Dicky
[3210 byte] By [dickylau] at [2007-11-11 10:27:14]
# 1 Re: Displaying the name of the new record (linked list)
Maybe inside the Database::insert function you do not need the rec = new Record line?
Viorel at 2007-11-11 20:58:47 >