Everything else is displaying in file as it is supposed to be other than the salary of the bank employee.
#include <stdio.h>
struct data {
char ide[50], name[50], bname[50], brname[50], con[10], sal[30];
};
int main() {
int n;
printf("Enter number of employees: ");
scanf("%d", &n);
struct data d[n];
for (int i = 1; i <= n; i++) {
printf("Enter data of employee %d\n", i);
printf("1) ID: ");
scanf("%s", d[i].ide);
printf("2) NAME: ");
scanf("%s", d[i].name);
printf("3) SALARY: ");
scanf("%s", d[i].sal);
printf("4) CONTACT: ");
scanf("%s", d[i].con);
printf("5) BANK NAME: ");
scanf("%s", d[i].bname);
printf("6) BRANCH NAME: ");
scanf("%s", d[i].brname);
}
FILE *fp;
fp = fopen("dbms.txt", "w");
for (int i = 1; i <= n; i++) {
fprintf(fp, "1) ID: %s\n2) NAME: %s\n3) SALARY: %s\n4) CONTACT: %s\n5) BANK NAME: %s\n6) BRANCH NAME: %s\n",
d[i].ide, d[i].name, d[i].sal, d[i].con, d[i].bname, d[i].brname);
}
fclose(fp);
}
Array indice in C starts from 0, not 1, and what to specify for array declaration is not the maximum index but the number of elements.
Therefore, your loop for (int i = 1; i <= n; i++)
with the array struct data d[n];
will lead to out-of-range access.
You should loop from 0
to n-1
instead of 1
to n
like this:
for (int i = 0; i < n; i++)
Also note that VLA (variable-length array) like struct data d[n];
may not work with large data size because it may be allocated on the stack with limited size. You should allocate memory on the heap via malloc()
instead like this:
struct data *d = malloc(sizeof(*d) * n);
if (d == NULL) {
/* allocateion failed */
exit(1);
}
You should add #include <stdlib.h>
to use malloc()
(and exit()
).
Checkers may say that you should use free()
to deallocate allocated memory after use, but it may not be required in the real world just before end of program execution.