Storing record of 100 employees using c language - c

Using c language how we can store 100 employees record like employee name,designation,salary in variables and how we can access them.

Conceptually in a nutshell, you can first create an "Emp" structure(struct), with attributes such as name, salary etc... Then create an array of (100) such Emp structs.
To access it, you just loop through this array, for each struct, you can access name, salary, etc..
Hope that helps.

Here an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSTR 50
#define MAXEMPLOYEES 100
typedef struct {
char name[MAXSTR];
char designation[MAXSTR];
float salary;
} Employee;
typedef struct {
Employee employeesArray[MAXEMPLOYEES];
int count;
} Employees;
void initEmployees(Employees*);
Employee readEmployee();
void addEmployee(Employees*, Employee);
void showAllEmployees(Employees);
int main()
{
int choice;
Employee newEmployee;
Employees employeesArchive;
initEmployees(&employeesArchive);
do{
printf("1. Add new Employee.\n");
printf("2. Show all Records.\n");
printf("0. Exit.\n");
printf("Select: ");
scanf("%d", &choice);
switch(choice){
case 1:
newEmployee = readEmployee();
addEmployee(&employeesArchive, newEmployee);
break;
case 2:
showAllEmployees(employeesArchive);
break;
}
}while(choice!=0);
return 0;
}
void initEmployees(Employees *_employees){
_employees->count = 0;
}
Employee readEmployee(){
Employee _newEmployee;
printf("NEW RECORD\n");
printf("-> Name: ");
scanf("%s", _newEmployee.name);
printf("-> Designation: ");
scanf("%s", _newEmployee.designation);
printf("-> Salary: ");
scanf("%f", &_newEmployee.salary);
return _newEmployee;
}
void addEmployee(Employees *_employees, Employee _newEmployee){
int index;
index = _employees->count;
strcpy(_employees->employeesArray[index].name, _newEmployee.name);
strcpy(_employees->employeesArray[index].designation, _newEmployee.designation);
_employees->employeesArray[index].salary = _newEmployee.salary;
_employees->count++;
printf("New Employee correctly added!\n");
system("pause");
}
void showAllEmployees(Employees _employees){
int i, allRecords;
allRecords = _employees.count;
for(i=0; i<allRecords; i++){
printf("#%d\nName: %s\tDesignation: %s\tSalary: %f\n",
i+1,
_employees.employeesArray[i].name,
_employees.employeesArray[i].designation,
_employees.employeesArray[i].salary);
printf("\n");
}
}

Better you create a linked list.
It's type of data structure in which you have to create a object which contain all information (of employee in this case) along with a pointers which point to other objects of list.
(Based on your question I must suggest you to Read what data structure is before moving forward..)
There are several types of data structures like single linked list ,circular linked list , double link list , tree , etc.. But here you can try most basic e.g. single link list for your requirement.
#include<stdio.h>
#include<stdlib.h>
#define LEN=20;
//this is our object definition
typedef struct EMPLOYER
{
char name[LEN],designation[LEN];
int salary;
struct EMPLOYER* next_object;
};
void add_employer_details();
void print_employers_details();
EMPLOYER** main_pointer;
char op;
int main()
{
printf("shall we start storing data of employee...?(y/n)\n");
scanf(" %c",&op);
while(op=='y' || op=='Y')
//to add new employee's detail
add_employer_detail();
//print whole database
print_employers_detail();
}
void add_employer_detail()
{
//creating a node
EMPLOYER *temp;
//allocating memory
temp=(EMPLOYER*)malloc(sizeof(EMPLOYER));
printf("enter details of employer...\n");
//feeling the data
gets(temp->name);
gets(temp->designation);
scanf("%d",&(temp->salary));
//making the link with other nodes
temp->next=main_pointer;
main_pointer=temp;
printf("want a new entry?(y/n)");
scanf(" %c",&op);
}
void print_employer_detail()
{
EMPLOYER* temp=*main_pointer;
while(temp)
{
printf(" name of employee : %20s\n designation of employee : %20s\n salary of employee : %8d\n",temp->name,temp->designation,temp->salary);
temp=temp->next;
}
}
Its always a good habit to allocate memory dynamically when it comes to data management system.But you always make sure that you are deallocating memory once you no longer need it to avoid memory leak. :)

Related

Understanding references to members in a struct within a struct, as well as how to dynamically allocate memory for struct members

I've looked at a few different questions with regards to the problem I am facing and while I feel like I've gained some insight I definitely have questions that I could use help with, so I wanted to solve a problem and get some help with the issues I'm facing in solving it.
I have an employee registry, I want to create a structure "Employee" that contains the data fields that I need for each employee. Within those fields I want another structure for their "Date of Birth" which has 3 ints within the struct - referring to month/date/year of birth. (See below)
typedef struct DOB {
int month;
int day;
int year;
} Birthdate;
typedef struct EmployeeInfo {
int empID;
char *firstName;
char *lastName;
Birthdate date;
double salary;
} Employee;
Now I want my program to output a menu of choices and prompt the user for input that could lead to several options those being:
Insert a new employee
Update/change info about an employee
Search for a specific employee
Display all information about all employees
int main() {
//create the array of Items
Employee * employeeRecord = (Employee * ) malloc(N * sizeof(Employee));
Birthdate * birthRecord = (Birthdate * ) malloc(N * sizeof(Birthdate));
int empID;
double salary;
Employee Employee;
Birthdate Birthdate;
char opt;
while (1) {
dispayMenu();
printf("Enter your Choice: ");
scanf(" %c",&opt);
switch(opt) {
case 'i':
printf("\nEnter empID: ");
scanf("%d", & Employee.empID);
printf("Enter firstName: ");
scanf("%s", Employee.firstName);
printf("Enter lastName: ");
scanf("%s", & Employee.lastName);
printf("Enter Date of Birth (month/day/year format): ");
scanf("%d-%d-%d", &Employee.date.month,&Employee.date.day,&Employee.date.year);
printf("Enter Employee salary: ");
scanf("%lf", & Employee.salary);
insertItem(employeeRecord, Employee);
break;
case 'u':
printf("\nEnter empID to update: ");
scanf("%d", & empID);
updateItem(employeeRecord, empID);
break;
case 's':
printf("\nEnter empID to search: ");
scanf("%d", &empID);
searchItem(employeeRecord, empID);
break;
case 'd':
printData(employeeRecord);
break;
case 'q':
quit(employeeRecord);
break;
default:
printf("%c is not a valid choice", opt);
}
}
}
The first question I have is - how can I dynamically update the size of the array that contains all the employees? I get a segmentation fault currently; I don't want to globally create the size of the array; but I know I only need to update it when I have to add an Employee to the registry - so when I call the insert function - but I don't know how to keep a count for a variable in main that updates when insert is called.
The second question is in regards to changing the date of birth - I know I have to use -> operator somewhere so that I can access the fields within the second structure, but when I use it currently it tells me that the type is mismatched - its an int but expects type char*. So how do I access data within the structures to change from the update() function.
void updateItem(Employee * employeeRecord, int empID) {
int i;
char chng;
for (i = 0; i < current_size; i++)
{
if (employeeRecord[i].empID == empID)
{
printf("What data do you wish to update?: ");
scanf(" %c", &chng);
switch (chng)
{
case '1':
printf("\nEnter new First Name: ");
scanf("%s", &Employee.firstName);
break;
case '2':
printf("\nEnter new Last Name: ");
scanf("%s", &Employee.lastName);
break;
case '3':
printf("\nEnter new Date of Birth: ");
// scanf("%d", &empID);
// searchItem(employeeRecord, empID);
break;
case '4':
printf("\nEnter new salary: ") break;
case '5':
printf("\nReturning to main menu.");
break;
default:
printf("%c is not valid, try it again.", opt);
}
}
break;
}
else{
printf("Employee Not Found");
}
}
I've described it above, but essentially can't seem to reference the items within a struct correct and am having trouble correctly calling functions from main - says the implicit declaration doesn't match the type of the function, but that might have to do with errors within those functions themselves.
You store your Employees in a dynamically allocated array, then use realloc() to resize the array:
void insertItem(Enployee **employees, size_t *n, Employee e) {
Employee *tmp = realloc((n+1) * sizeof(Employee));
if (!tmp) {
// fail
}
*employees = tmp;
memcpy(*employees + *n, e, sizeof(Employee));
(*n)++;
}
int main(void) {
// ...
Employee *employees = NULL;
size_t n = 0;
// ...
case 'i': {
Employee *e = malloc(sizeof(Employee));
scanf("%d", e->empID);
// ...
insertItem(&employees, &n, e);
}
// ...
}
As employees and n belong together it would make sense to create a struct to hold them.
Within the Employee struct Birthdate date is also a struct. You use . to access members of a struct via a value, and -> if you have a pointer. In updateItem() you pass in an Employee *employeeRecord and use it as an array so you you either do:
employeeRecord[i].date.month = ...
// or
(employeeRecord + i)->date.month = ...
You can only reference functions already declared so you want main() last. The other good option is to add declarations for your functions at the top.

Make a 2D array in a struct, store strings inside array

I have to make a library system using structs and pointers, that registers a person with their name, ID, phone number, and the name of the books (maximum 3). I have created a struct for every borrower, and I am trying to store input taken by the user, specifically at the part of getting the book titles, to store into an array of other structs (for other borrowers). I have to be able to free the locations of the borrowers once they return all books, so I'd have to use dynamic memory for that.
This is the code I have so far, not sure how exactly I would go about storing every borrower using pointers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_NAME_SZ 256
#define CLEAR() system("CLS")
struct borrower
{
char name[20];
char lastName[20];
char id[7];
char phoneNumber[10];
char titleOfBook[3][20];
};
int main(void)
{
struct borrower b;
char op;
do
{
puts("\n1) Register borrower");
puts("2) Find by ID");
puts("3) Show All");
puts("4) Erase by ID");
puts("0) Exit");
printf("Option:");
setbuf(stdin, 0);
opc=getchar();
switch(op)
{
case '1':
RegisterBorrower(&b);
break;
case '2':
//showID();
break;
case '3':
//showAll();
break;
case '4':
//erase();
break;
case '0':
break;
}
}while (op!=48);
return 0;
}
void RegisterBorrower(struct borrower *b)
{
CLEAR();
setbuf(stdin,0);
printf("ID: "); gets(p->id);
printf("Name: "); gets(p->name);
printf("Last Name: "); gets(p->lastName);
setbuf(stdin,0);
printf("Phone Number: "); gets(p->phoneNumber);
int numberOfBooks=0, cont=0, i;
char bookTitle[20];
printf("How many books do you want to take out?(max 3): ");
scanf("%d", &numberOfBooks);
setbuf(stdin,0);
if(numberOfBooks<=3 && numberOfBooks>0)
{
for(i=0; i<numberOfBooks; i++)
{
setbuf(stdin,0);
printf("Book Title: "); gets(bookTitle);
strcpy(p->titleOfBook[i][0], bookTitle);
}
}else
{
printf("You cannot take out this amount of books.");
}
}
Everything "works" (doesn't crash) up until the part I ask for the book titles, it only runs once. Any help would be greatly appreciated.
EDIT:
My problem was that I used
strcpy(p->titleOfBook[i][0], bookTitle);
which only copies to one character because of the [0]. I changed it to
strcpy(p->titleOfBook[i], bookTitle);
and it worked fine.

Structure using Pointers and Function to store and retrieve data

struct account
{
struct //A structure inside a structure
{
char lastName[10];
char firstName[10];
} names; //structure is named as 'name'
int accountNum;
double balance;
};
int main()
{
struct account record;
int flag = 0;
do
{
nextCustomer(&record);
if ((strcmp(record.names.firstName, "End") == 0) && //only when the first name entered as "End"
(strcmp(record.names.lastName, "Customer") == 0)) //and last name entered as "Customer", the loop stops
flag = 1;
if (flag != 1)
printCustomer(record);
}
while (flag != 1);
}
void nextCustomer(struct account *acct)
{
printf("Enter names (firstName lastName):\n");
//scanf("%s, %s", acct->firstName, acct->lastName); //have no idea why first and last name cant be found although im aware thats its a structure inside a structure
printf("Enter account number:\n");
//scanf("%d", acct->accountNum);
printf("Enter balance:\n");
scanf("%f", acct->balance);
}
void printCustomer(struct account acct)
{
printf("Customer record: \n");
printf("%d", acct.accountNum); //can't seem to retrieve data from the strcture
}
Hi guys, i am new to c, and i managed to hardcode data on structures, and print our their respective value. Currently, i am working on using a pointer to store the respective data, as well as function to print out their data. Can anyone help me on why i cant store and retrieve my data? I dont need the answers, just the logic flow is sufficient.
Followin changes are needed to your nextCustomer function, you are directly accessing firstName and lastName using acct, but they are present inside names
so you have to use acct->names.firstName and acct->names.lastName
void nextCustomer(struct account *acct)
{
printf("Enter names (firstName lastName):\n");
scanf("%s%s", acct->names.firstName, acct->names.lastName); //have no idea why first and last name cant be found although im aware thats its a structure inside a structure
printf("Enter account number:\n");
scanf("%d", &acct->accountNum);
printf("Enter balance:\n");
scanf("%lf", &acct->balance);
}
void printCustomer(struct account acct)
{
printf("Customer record: \n");
printf("F: %s\n", acct.names.firstName);
printf("L: %s\n", acct.names.lastName);
printf("A: %d\n", acct.accountNum); //can't seem to retrieve data from the strcture
printf("B: %lf\n", acct.balance);
}

printing with type long

I'm working on my school project form data structure and I'm having a problem with the type long.
I want to design a small project like a university registration system.
First the person get to chose if he want to register or exit.
If he want to register then he will enter his name and gpa to select the major that is available based on his gpa and the system will generate an id automatically.
The problem is the id is not incremented correctly.
Additional info:
I'm using doubly linked list structure
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<string.h>
struct student{
char name[30];
int GPA;
unsigned long ID;
char colloege[100];
student *next, *prev;
};
student *stu, *cur, *head, *tail;
void insertfront();
void displaylist(){
unsigned long id=214000000;
cur=head;
printf(" ");
if(cur==NULL)
printf(" ");
else
while(cur!=NULL){
printf("Name:%s\t",cur->name);
printf("ID:%d\t",cur->ID=id++);
printf("GPA:%d\t",cur->GPA);
printf("Colloege of:%s\t",cur->colloege);
printf("\n");
cur=cur->next;
}
}
void main(){
clrscr();
int x;
printf("\n\t\t\t\t******* King Faisal University *********\n");
while(x!=2){
printf("\n press 1 to insert your information ,press 2 to exit\n");
scanf("%d",&x);
insertfront();
displaylist();
}
stu=NULL;
cur=NULL;
head=NULL;
tail=NULL;
getch();
}
void insertfront(){
int x,c;
stu=(student*)malloc(sizeof(student));
fflush(stdin);
printf("Enter your name:\n");
scanf("%[^\n]%*c",stu->name);
printf("Enter your GPA:\n");
scanf("%ul",&stu->GPA);
printf("\n Available Colloeges\n");
if(stu->GPA>=85)
{
printf("1.Colloege of Medicine\n 2.Colloege of Engenering\n 3.Colloege of Computer Science\n 4.Colloege of Business\n 5.Colloege of Art\n");
printf("Enter the colloege number \n");
scanf("%d",&c);
switch(c){
case 1: strcpy(stu->colloege,"Medicien");break;
case 2: strcpy(stu->colloege,"Engenering");break;
case 3: strcpy(stu->colloege,"Computer Science");break;
case 4: strcpy(stu->colloege,"Business");break;
case 5: strcpy(stu->colloege,"Art");break;
}
}
else if(stu->GPA>=75)
{
printf("1.Colloege of Computer Science\n 2.Colloege of Business\n 3.Colloege of Art\n");
printf("Enter the colloege number\n");
scanf("%d",&c);
switch(c){
case 1: strcpy(stu->colloege,"Computer Science");break;
case 2: strcpy(stu->colloege,"Business");break;
case 3: strcpy(stu->colloege,"Art");break;
}
}
else
strcpy(stu->colloege,"Art");
if(head==NULL)
{
stu->next=NULL;
stu->prev=NULL;
head=stu;
tail=stu;
}
else
{
stu->next=head;
stu->prev=NULL;
head->prev=stu;
head=stu;
}
}
You are using an incorrect conversion in your program
printf("ID:%d\t",cur->ID=id++);
// cur->ID is of type unsigned long
// %d is used for values of type int
To print a value of type long you need to use "%ld" in the printf() conversion
long longvalue = 42;
printf("%ld\n", lonvgalue);
To print a value of type unsigned long you need to use "%lu" in the printf() conversion
unsigned long ulongvalue = 42;
printf("%lu\n", ulongvalue);
In addition to the format specifier being wrong, you have a problem with assigning ID:s.
Your code assigns new ID:s every time you display the list.
I would generate the ID only once for each student record, when the record is created.
So add this in insertfront:
stu->ID=id++;
and change the printing in displaylist to:
printf("ID:%lu\t",cur->ID);
and move the declaration of id either to global scope (outside of any function) or as a static variable inside insertfront:
static unsigned long id=214000000;

Taking in unique inputs in a struct array in C

I am writing a program to create a structure named 'student'. I need to input various data about a particular student. Here is my program till now.
#include<stdio.h>
#include<stdlib.h>
struct student
{
char* name;
int id;
float marks_1;
float marks_2;
};
void main()
{
int num, var_i, var_j, var_k, var_l, duplicated_id = 0;
printf("Enter number of students\n");
scanf("%d", &num);
struct student s[num];
printf("Enter the data for the students\n");
for (var_i = 0; var_i < num; var_i++)
{
var_j = var_i + 1;
printf("Enter name of student_%d\n", var_j);
scanf(" %[^\n]%*c", &s[var_i].name);
printf("Enter id of student_%d\n", var_j);
scanf("%d", &s[var_i].id);
for (var_k = 0; var_k < var_i; var_k++)
{
if (s[var_k].id == s[var_i].id)
{
printf("Duplicate Id, program will exit");
return;
}
}
printf("Enter marks(sub_1) of student_%d\n", var_j);
scanf("%d", &s[var_i].marks_1);
printf("Enter marks(sub_2) of student_%d\n", var_j);
scanf("%d", &s[var_i].marks_2);
}
}
In the following for loop I am checking all the previously entered 'id' values to check if there is a duplicate. In case of a duplicate, the program will exit.
for(var_k=0;var_k<var_i;var_k++)
{
if(s[var_k].id==s[var_i].id)
{
printf("Duplicate Id, program will exit");
return;
}
}
Now instead of exiting the program I want to prompt the user to enter a different value. This goes on till he enters a unique value. How should I do it?
Any help appreciated.
This is wrong:
scanf(" %[^\n]%*c", &s[var_i].name);
You're passing the address of the pointer member name (i.e. you're passing a char **) to scanf() which per the format string, is expecting a char* and enough memory to hold the data it subsequently reads. This is invalid, is undefined behavior, and blindly overwrites data in the s[] array. Frankly I'm amazed this doesn't seg-fault your process.
Change this:
struct student
{
char* name;
int id;
float marks_1;
float marks_2;
};
To this:
struct student
{
char name[128]; // or some other suitable size.
int id;
float marks_1;
float marks_2;
};
And change this:
scanf(" %[^\n]%*c", &s[var_i].name);
To this:
scanf(" %[^\n]%*c", s[var_i].name);
I strongly suggest a size-limiter on that scanf() call as well, but I leave that to you to discover. Read about the API here.
Just use a loop.
here is some psudocode
bool isDuplicate = false
do
{
GetInput()
isDuplicate = CheckForDuplicate()
}while(isDuplicate);

Resources