This may be a simple problem to solve but I have spent way too much time on it.
If I am reading from a file and I have a structure array of size 100 but only enough data in the file to fill 3 structures how would you keep count of the 3 structures? My problem is that I read from the file and I fill the 3 structures in the array but because my structure array is of size 100 I end up filling up the rest with blanks. I do not really care about this but my problem is that if I print out the structure array I print my 3 structures with data but then also print the remaining 97 blank structures which makes for one blank screen. I know the solution to this is to keep track of the entries with data and ignore the rest but for the life of me I am coming up blank.
I intend to make it so that I add an entry in switch 1 but until I can keep track of the entries I'm stuck.
A push in the right direction would be great at this point.
The data in the file looks like this:
Bob
The
Builder
King
555-555-1234
192
Patric
Augustus
Caesar
Bully
555-555-5678
202
Tsula
Cal
Jones
Nut
555-555-4567
112
Code:
#include<iostream>
#include <fstream>
using namespace std;
#define N_ENTRIES 100
struct directory
{
char firstName[30];
char lastName[30];
char middleName[30];
char title[30];
char phoneNumber[20];
char officeNumber[10];
} entry[N_ENTRIES];
int main()
{
ifstream inData;
ofstream outData;
char option;
int n;
cout << "Welcome to the CS ltd telepone directory" << endl << endl;
cout << "Please enter your choice: " << endl << endl;
cout << "1 : Add new entry" << endl;
cout << "2 : Display Directory" << endl;
cout << "3 : Remove and entry" << endl;
cout << "4 : Exit" << endl << endl;
cout << "Choice: ";
cin >> option;
cout << endl;
switch(option)
{
case '1': inData.open("direct.dat");
cout << "Opening file: direct.dat" << endl << endl;
if(!inData)
{
cout << "ERROR in opening direct.dat" << endl << endl;
return 1;
}
else
if(inData)
{
n=0;
for(n = 0; n < N_ENTRIES; n++)
{
inData.get(entry[n].firstName, 30, '\n');
inData.get();
inData.get(entry[n].middleName, 30, '\n');
inData.get();
inData.get(entry[n].lastName, 30, '\n');
inData.get();
inData.get(entry[n].title, 30, '\n');
inData.get();
inData.get(entry[n].phoneNumber, 20, '\n');
inData.get();
inData.get(entry[n].officeNumber, 10, '\n');
inData.get();
cout << entry[n].firstName << " " << entry[n].middleName
<< " " << entry[n].lastName << endl;
cout << entry[n].title << endl;
cout << entry[n].phoneNumber << endl;
cout << entry[n].officeNumber << endl << endl;
}
}
break;
}
return 0;
}