My problem: create a program that can read a given data file and list the names. Use dynamic memory allocation. Be able to add and delete names to this file.
I'm not worried about adding a menu and such to pretty up the program, but I haven't been able to figure out the read/write to a file business. I've tried so many things now that it's hard remember what I'm doing anymore. Any help or suggestions would be GREATLY apprecieated. Thanks.
My (most easily followed) code thus far:
#include <iostream.h>
#include <iomanip.h>
#include <conio.h>
#include <fstream.h>
#include <stdlib.h>
#include <string.h>
class Names
{
public:
char name[15];
};
int readNameArray(const char filename[], Names *a[], int nmax)
{
ifstream nameFile("c:\\temp\\Names.dat" , ios::in | ios::nocreate);
if (!nameFile)
{
cerr << "File could not be opened." << endl;
exit(1);
}
int counter ;
for (counter = 0; !nameFile.eof() && counter < nmax; ++counter)
{
nameFile >> a[counter] ->name;
nameFile.ignore(256, '\n');
}
nameFile.close();
return counter;
}
void addName(const char filename[], const Names * const a[], int n)
{
if (n <=0)
return;
ofstream nameAdd("c:\\temp\\Names.dat" , ios::app | ios::nocreate);
if (nameAdd.fail() )
{cout << "Could not open " << filename << endl;
exit(1);
}
for (int lcv=0; lcv<n; lcv++)
{
nameAdd << a[lcv]->name << ' ' << endl;
}
nameAdd.close();
}
void freeNameArray(Names *a[], int n)
{
for (int k = 0; k < n; k++)
delete a[k];
delete [] a;
}
void main(void)
{
char inNames[11] = {"input"};
char outNames[11] = {"output"};
int size;
cout << "How many names do you want to enter? ";
cin >> size;
int n;
Names **table = new (Names *); //[size];
n = readNameArray(inNames, table, size);
cout << "There are "<< n << " names in the list."<< endl;
addName(outNames, table, n);
freeNameArray(table, n);
}