Rejects duplication

Hello everyone i need help for an assignment for our prog class..

We were assigned to make an employee log sheet that records employee numbers, employee name and the salary.

our professor told us that our code should be able to detect if an employee number is duplicated and rejects the last person who have inputted a similar employee number.

thank you in advance :)

EDIT: my codes are in my last post
Last edited on
Err... so.... what do you want from us?
Umm what i would like to have is a code to detect if the added record have a duplicated employee number on a previous existing record and rejects his input, and i can't seem get my code right :P
Umm what i would like to have is a code to detect if the added record have a duplicated employee number on a previous existing record and rejects his input,


After you get the input, check all existing employees to see if they match what the user input.

If it matches any of them, then reject the input. It's pretty straightforward.

As a general rule we don't provide full solutions, but if you make an attempt on your own and post what you have, we can help refine it.

and i can't seem get my code right :P


You'll need to be more specific. =P
You might consider set<string> to detect duplicates.
You'll need to be more specific. =P


here it is..
1
2
3
4
5
6
7
if("the number of employee"=="my variable"[x]."employee number"){
.....
}

else {
// if the add was a success
}


i don't know where will i put those codes, i tried adding it on my add record case (case 1) but it doesn't seem to work..

Last edited on
bump!
I'm not even going to look at this until it's presented more neatly. Hard to read code is hard to fix code. Don't be afraid of whitespace.
Last edited on
I'm not even going to look at this until it's presented more neatly. Hard to read code is hard to fix code. Don't be afraid of whitespace.


here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#include <cstdlib> // system()
#include <conio.h> // getch()
#include <fstream>
#include <sys\stat.h> // stat(status of a file)
#include <iostream>
using namespace std;

/////////////	Data types /////////////

struct Employee_Record // Employee record
{
	int ID;
	char NAME[30];
	int SALARY;
	bool deleted;
};

/////////////	Variable Declarations & Constants /////////////

#define EMPLOYEE_FILE_NAME "Employees.txt" // name of the database file to store employees informations

Employee_Record Employee;
char choice; // for choice in menu
fstream *fs = NULL, *fs1 = NULL;// file streams for files : fs -> 'Employee', fs1 -> 'temp'
bool deletion = false; // if any record has been deleted

/////////////	Function Prototypes /////////////

void closeFile(fstream *); // closes a file with its pointer, then deletes the file pointer
bool isFileExist(const char *); // check if a file exists

/////////////	Main /////////////
int main()
{
	while (true)
{
	do ////// Menu //////
{
	system( "cls" ); // clear screen
	cout << "\n < Employees Database > \n\n";
	cout << "(1) Add a new Record \n";
	cout << "(2) Modify an existing Record\n";
	cout << "(3) Delete an existing Record \n";	
	cout << "(4) Display Records \n";
	cout << "(5) Exit \n\n";
	cout << " Enter a choice (1-5) : " << flush;
	choice = getch();
}
	
while ( choice < '1' || choice > '5'); // while we have no good(between 1 and 5), show menu again

system( "cls" );

// to modify, delete or display records, database file should exist, then we have some records	
	if (choice == '2' || choice == '3' || choice == '4')
{
	if (!isFileExist(EMPLOYEE_FILE_NAME)) // if database file doesn't exist
{
	cout << "\n Database file ('" << EMPLOYEE_FILE_NAME << "') doesn't exist, then there are no records." << endl;
	system("pause");
	continue; // show the menu again
}
}

switch ( choice )
{
	int recs_num; // number of records before the record for modifying(deletion)
	int id;

case '1' : ////// Add Record //////

	cout << "\n\t\t < Entering a new record > ";
	cout << "\n Enter the following informations for the new record : ";
	cout << "\n EMPLOYEE NUMBER : ";
	cin >> Employee.ID;
	cout << "\n EMPLOYEE NAME : ";
	cin >> Employee.NAME;
	cout << "\n SALARY : ";
	cin >> Employee.SALARY;

Employee.deleted = 0;

fs = new fstream( EMPLOYEE_FILE_NAME, ios::out | ios::app | ios::binary );

if (!fs)
{
	cout << "\n Can't open or create '" << EMPLOYEE_FILE_NAME << "' file" << endl;
	system("pause");
	break;
}
	fs->write( (char *) &Employee, sizeof(Employee) );

	closeFile(fs);

	cout << "\n Record added." << endl;
	system("pause");
	break;

case '2' : ////// Modify Record //////

	cout << "\n Enter the employee number that you want modify its information : ";
	cin >> id;

fs = new fstream( EMPLOYEE_FILE_NAME, ios::in | ios::out | ios::binary );

if (!fs)
{
	cout << "\n Can't open or create '" << EMPLOYEE_FILE_NAME << "' file" << endl;
	system("pause");
	break;
}

recs_num = -1;

while (fs->read( (char *) &Employee, sizeof(Employee) ))
{
	recs_num++;
	if ( Employee.ID == id && !Employee.deleted)
	break;
}

if (fs->eof()) // if (the record is not in the file || it's there but it's deleted)
{
	cout << "\n Your specified employee doesn't exist in file." << endl;
	closeFile(fs);
	system("pause");
	break;
}

	cout << "\n Enter new informations for this record : ";
	cout << "\n EMPLOYEE NUMBER : ";
	cin >> Employee.ID;
	cout << "\n EMPLOYEE NAME : ";
	cin >> Employee.NAME;
	cout << "\n SALARY : ";
	cin >> Employee.SALARY;

	fs->seekp ( sizeof(Employee) * recs_num, ios::beg ); // go to the first of the record to be modified
	fs->write( (char *) &Employee, sizeof(Employee) );

	closeFile(fs);

	cout << "\n Record is modified." << endl;
	system("pause");
	break;

case '3' : ////// Delete Record //////

cout << "\n Enter employee's number, for deletion : ";
cin >> id;

fs = new fstream( EMPLOYEE_FILE_NAME, ios::in | ios::out | ios::binary );

if (!fs)
{
	cout << "\n Can't open or create '" << EMPLOYEE_FILE_NAME << "' file." << endl;
	system("pause");
	break;
}

recs_num = -1;

while (fs->read( (char *) &Employee, sizeof(Employee) ))
{
	recs_num++;
	if ( Employee.ID == id && !Employee.deleted ) // if user deleted an employee then added another one with the same ID in the same instance of program runs, deleted employee is still there, then we should go through all the file
	break;
}

if (fs->eof()) // if (the record is not in the file || it's there but it's deleted)
{
	cout << "\n Your specified employee doesn't exist in database file." << endl;
	closeFile(fs);
	system("pause");	
	break;
}

Employee.deleted = 1;

fs->seekp ( sizeof(Employee) * recs_num, ios::beg );
fs->write( (char *) &Employee, sizeof(Employee) );

closeFile(fs);

deletion = true; // we have some deleted records

cout << "\n Record is deleted." << endl;
system("pause");
break;

case '4' : // Display Records

////// Print Salaried records...
fs = new fstream( EMPLOYEE_FILE_NAME, ios::in | ios::binary );

if (!fs)

{
	cout << "\n Can't open or create '" << EMPLOYEE_FILE_NAME << "' file." << endl;
	system("pause");
	break;
}

// display column titles
	cout << "\n";
	cout << "                           < Employee List >                           \n";
	cout << "-----------------------------------------------------------------------\n";
	cout << "Employee Number                 Name                            Salary \n";
	cout << "-----------------------------------------------------------------------\n";	

	while (fs->read( (char *) &Employee, sizeof(Employee) )) // display records
{
{
	cout << Employee.ID << "\t\t\t\t" << Employee.NAME << "\t\t\t\t" << Employee.SALARY <<endl;
}
}
	cout << "-----------------------------------------------------------------------\n";
	cout << "\n "; system("pause");

closeFile(fs);

////// Back Function...	
system( "cls" );

fs = new fstream( EMPLOYEE_FILE_NAME, ios::in | ios::binary );

if (!fs)
{
	cout << "\n Can't open or create '" << EMPLOYEE_FILE_NAME << "' file." << endl;
	system("pause");
	break;
}
	while ( fs->read( (char *) &Employee, sizeof(Employee_Record) ) )
{
}

	cout << "\n To see menu, "; system("pause");
	closeFile(fs);
	break;


case '5' : // Exit

if (deletion) // if there is any deletion, then update database file (create a new temp file that doesn't have deleted records, then remove the old database file and rename temp file to database file name)
{
	cout << "\n Updating '" << EMPLOYEE_FILE_NAME << "' File..." << endl;

	fs = new fstream( EMPLOYEE_FILE_NAME, ios::in | ios::binary );

if (!fs)
{
	cout << "\n Can't open '" << EMPLOYEE_FILE_NAME << "' file, then Updating is incomplete." << endl;
	system("pause");
	system( "cls" );
	return 1;
}

	fs1 = new fstream( "temp", ios::out | ios::binary);

if (!fs1)
{
	cout << "\n Can't create temp file, then Updating is incomplete." << endl;
	system("pause");

	closeFile(fs);
	system( "cls" );
return 1;
}

// write nondeleted records to the temp file
while (fs->read( (char *) &Employee, sizeof(Employee) ))
if ( !Employee.deleted )
fs1->write( (char *) &Employee, sizeof(Employee) );

closeFile(fs);
closeFile(fs1);

if( remove( EMPLOYEE_FILE_NAME ) == -1 ) // if there is an error
{
	cout << "\n Can't delete '" << EMPLOYEE_FILE_NAME << "' file, then Updating is incomplete." << endl;
	system("pause");

	system( "cls" );
return 1;
}

struct stat st; // to check size of the temp file
int res = stat( "temp", &st );

if (st.st_size == 0) // if all of records are deleted then the temp file size is zero	
	remove( "temp" ); // we have no records, then no database file is needed, just delete the temp file
else

if ( rename ("temp", EMPLOYEE_FILE_NAME) )
{
	cout << "\n Can't rename temp file, then Updating is incomplete." << endl;
	system("pause");

	system( "cls" );
return 1;
}

	cout << "\n Updating database file completed." << endl;
	system("pause");
}

system( "cls" );
return 0;

break;
} // end 'switch'
} // end 'while'

return 0;
} // end 'main()'


/////////////	Function Definitions /////////////

void closeFile(fstream *fs)
{
	fs->close(); // close the file
	delete fs;
	fs = NULL;
}

bool isFileExist(const char * file_name)
{	
	struct stat st; // to check status of file
	int res = stat( file_name, &st );

return (res == 0); // if file exists	
}


i rearranged it a little so its easier to read, but honestly i have no idea how to present a code well so please bear with me :|
closed account (zb0S216C)
What's going on with your code? I see memory allocation, Pointers and Type-casting.

For a simple program that reads data from a file and check for a duplicate number/ID, it's a bit too much. I'll help you if you post a sample line from the log sheet what your program is reading from. This is my version of your code, p4neng.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include <fstream>
#include <string>
#include <vector>

using std::vector;
using std::string;
using std::ifstream;
using std::string;

struct EmployeeRecord
{
    EmployeeRecord( const int NewID, const string NewName, const int NewSalary, const bool NewDeleted )
    {
        ID = NewID;
        Name = NewName;
        Salary = NewSalary;
        Deleted = NewDeleted;
    }

    int ID;
    string Name;
    int Salary;
    bool Deleted;
};

// Employee records.
vector < EmployeeRecord > EmployeeRecords;

// Duplicate searcher.
bool IsDuplicateID( const EmployeeRecord &ThisRecord )
{
    // Compare the ID's.
    for( unsigned Index( 0 ); Index < EmployeeRecords.size( ); Index++ )
    {
        // Compare all the identifiers.
        if( ThisRecord.ID == EmployeeRecords.at( Index ).ID )
        {
            // ID conflict.
            return true;
        }
    }

    // No duplicates.
    return false;
}

// Employee deleter.
bool DeleteEmployee( const EmployeeRecord &Employee )
{
    // Search for the employee using the identifier.
    for( unsigned Index( 0 ); Index < EmployeeRecords.size( ); Index++ )
    {
        // Found the employee.
        if( EmployeeRecords.at( Index ).ID == Employee.ID )
        {
            // Remove the employee.
            EmployeeRecords.erase( EmployeeRecords.begin( ) += Index );

            // Finished.
            return true;
        }
    }

    // Failed. No employee matched.
    return false;
}

// Log sheet loader.
bool LoadLogSheet( const string &LogFilename )
{
    // Setup the loader.
    ifstream Log;
    Log.open( LogFilename.c_str( ) );

    // Has the log file been opened? Is the file even valid?
    if( Log.is_open( ) == false )
    {
        // Failed. The file is either invalid or the filename is wrong.
        return false;
    }

    // Read one line at a time with each pass. Note: where 1( in the for-looop condition ) is
    // the amount of lines to read from the file.
    for( unsigned Line( 0 ); Line < 1; Line++ )
    {
        // ID buffer.
        unsigned ExtractedID( 0 );

        // Extract the ID.
        Log >> ExtractedID;

        // Name buffer.
        string ExtractedName( "Nameless" );

        // Extract the name.
        Log >> ExtractedName;

            // Replace any underscores in the name with a space.
            for( unsigned Index( 0 ); Index < ExtractedName.length( ); Index++ )
            {
                // Compare the character.
                if( ExtractedName.at( Index ) == '_' )
                {
                    ExtractedName.at( Index ) = ' ';
                }
            }

        // Salary buffer.
        int ExtractedSalary( 0 );

        // Extract the salary.
        Log >> ExtractedSalary;

        // Deleted buffer.
        bool ExtractedDeleted( false );

        // Extracted the deleted.
        Log >> ExtractedDeleted;

        // Create the new employee.
        EmployeeRecord NewRecord( ExtractedID, ExtractedName, ExtractedSalary, ExtractedDeleted );

        // Check for a duplicate employee record.
        if( IsDuplicateID( NewRecord ) == false )
        {
            // Safe to add the new employee.
            EmployeeRecords.push_back( NewRecord );
        }

        else
        {
            //...
        }
    }

    // Close the file now that we have finished.
    Log.close( );

    // Success.
    return true;
}

int main( )
{
    // Do menu here...

    return 0;
}


Here is the file I was reading from:
62354 John_Doe 200 1

EDIT--------------8<------------------------------------------------------------------------------
i rearranged it a little so its easier to read

No offence intended but, it hasn't helped all that much.
Last edited on
Topic archived. No new replies allowed.