If(int IDnumvariable == structname[counter].IDnumber) Not working [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Im stuck on a situation with my book borrow function, The problem is when i have to compare user entered teacher id with an existing id in the teacherfile.
my id data types for both are integer so i used:
void tborrow() //2.1
{
int bksb=0;
int tbid2 =0;
struct books book[50];
struct teachers teach[50];
int x=0;
int c=0;
int i=0;
int tid=0;
int tid2=0;
int tbid=0;
FILE *teacherp;
FILE *bkbp;
teacherp= fopen("TeacherFile.txt", "r+");
if(teacherp!=NULL) //Checks if Teacher File was created successfully
{
printf("Teacher File Successfully Opened\n\n\n");
printf("Enter Teacher's ID# :");
scanf("%d",&tid);
while(1) // Loop till end of file
{
fflush(stdin);////flushes buffer
fscanf(teacherp,"%s %d %s %s %d ",teach[i].Teachname,&teach[i].IDnum,teach[i].contactnum,teach[i].Faculty,&teach[i].bksborrowed);
tid2= tid2 + teach[i].IDnum;
if (tid == tid2)
{
system("cls");
printf("Teacher ID Confirmed\n\n");
printf("\n\n----Teacher Information-----"); //check if correctly entered
printf("\nName: %s ", teach[i].Teachname);
printf("\nID #: %d " ,teach[i].IDnum);
printf("\nContact #: %s ", teach[i].contactnum);
printf("\nFaculty: %s " ,teach[i].Faculty);
printf("\nBooks Borrowed: %d " ,teach[i].bksborrowed);
printf("\n-----------------------------\n");
printf("\nIs your account? 1-Yes 0=No : ");
scanf("%d",&c);
fflush(stdin);//flushes buffer after scanf
if (c==1)//if yes find and borrow book
{
bksb = bksb+teach[i].bksborrowed;
if (bksb < 2)// if teacher has less than 2 books borrowed
{
printf("\nThis account currently has %d books borrowed",teach[i].bksborrowed);
bkbp = fopen("BookFile.txt","r+");
if(bkbp!=NULL) //Checks if Book File was created successfully if yes search for book and borrow
{
printf("Enter Book ISBN # :");
scanf("%d",&tbid);
while(1)
{
fscanf(bkbp,"%s %s %d %d %s %d %d-%d-%d %d-%d-%d ",book[x].Title, book[x].Author, &book[x].Accessionnum, &book[x].ISBN, book[x].Available, &book[x].bid, &book[x].bdate->m, &book[x].bdate->d, &book[x].bdate->y, &book[x].rdate->m, &book[x].rdate->d, &book[x].rdate->y);
tbid2 = tbid2 + book[x].ISBN;
if (tbid == tbid2)
{
printf("\n\n-------Book Information-------"); //check if correct book found
printf("\nTitle: %s", book[x].Title);
printf("\nAuthor: %s" ,book[x].Author);
printf("\nAccession#: %d" ,book[x].Accessionnum);
printf("\nISBN#: %d", book[x].ISBN);
printf("\nAvailability(Y-N): %s" ,book[x].Available);
printf("\nBorrowers ID#: %d ",book[x].bid);
printf("\nBorrow Date: %d-%d-%d ",book[x].bdate->m,book[x].bdate->d,book[x].bdate->y);
printf("\nReturn Date: %d-%d-%d ",book[x].rdate->m,book[x].rdate->d,book[x].rdate->y); //Prints user entry to screen for confirmation
printf("\n------------------------------\n");
printf("\nIs this the book you are looking for? 1-Yes 0=No : ");
scanf("%d",&c);
fflush(stdin);//flushes buffer after scanf
if (c==1)//if yes print into file
{
book[x].bid=tid2;
bksb++;
teach[i].bksborrowed=bksb;
printf("\n Book %s has been borrowed by %s %d",book[x].Title,teach[i].Teachname,teach[i].IDnum);
fclose(bkbp);
printf("\n\nReturning to previous account");
_getch();
break;
TeacherAcc();
}
/*else
{
fclose(bkbp);
system("cls");
printf("\nStarting over book borrowing!");
break;
tborrow();
}*/
}
else
//if we encountered the end of the file on the last attempt
//to read data then break out of the read loop
if( feof(bkbp) ) //If end of file is reached break out of loop
{
break;
}
++x;
}
}else // if book file failed to open
{
printf("Error!, Restarting Teacher Book Borrowing System. Press Enter to continue");
getchar();
tborrow();
}
}else if (teacher[i].bksborrowed == 2) // if teacher has already borrowed 2 books
{
printf("\nThis account already has %d books borrowed",teach[i].bksborrowed);
printf("\nGoing back to previous menu");
_getch();
system("cls");
TeacherAcc();
}
}
else if (c==0) //runs the Teacher borrow function if wrong account
{
system("cls");
printf("\nRe-Enter Teacher ID!");
tborrow();
}
}else // else if teacher id not found
{
printf("\nID %d not found, Please re-enter a valid ID \n Press enter to try again",tid);
_getch();
system("cls");
tborrow();
}
if( feof(teacherp) ) //If end of file is reached break out of loop
{
break;
}else
i++;
}//end of continuous loop
fclose(teacherp); //close the file when done
} //if file created successfully
else //Teacher file failed to load, restarts function to correctly open Teacher
{
printf("Error!, Restarting Teacher System. Press Enter to continue");
getchar();
system("cls");
}
printf("\n\nReturning to previous menu, Press Enter to continue \n");
fflush(stdin);//flushes buffer so getchar works properly
getchar();
system("cls");
TeacherAcc();
}//borrow function end
but it is not correctly comparing or storing the id i read from the file, and the file exists and the has the stored id for tests
attached is the block of code from my teacher borrow function
any help would be appreciated
i was thinking of making the id datatypes char and use strcmp(userentered,struct[count].idnum)

(form the comments)
Remove tid2= tid2 + teach[i].IDnum;.
Yes, you can use if (tid == teach[i].IDnum)
However, look at what your while(1) loop in tborrow is doing:
while(1)
read a teacher from the file
is the teacher the right one?
yes - do something
no - print an error and recursively call tborrow again.
Think about how you would do this if you were looking for a teacher by hand in a list on paper - would you look at the first teacher in the list, then give up and start again if it wasn't the right one?

Related

How to add line number to only a specific line in a file

I'm creating the inputs of a disease and information on it. The disease should have a number beside it but the remaining inputs should remain as is. How can i add the information to a file but have the disease number increment as it reads new inputs as the program closes?
I've tried using a variable to print the disease number as it goes, but i dont understand how to increment it.
void CreateNew(){
int diseasenum=1;
FILE*fptr;
fptr = fopen("Lifeline Medical & Diagnostic Center.txt", "a+");
if(fptr == NULL)
{
printf("Error! There is no file to write to. Please Create a file");
exit(1);
}
fflush(stdin);
printf("Enter the name of the disease you would like to give detail of: ");
gets(Dissarray.Disease);
if()
fprintf(fptr,"%d\tDisease: %s\n\n",diseasenum,Dissarray.Disease);
printf("\n");
fflush(stdin);
Dissarray.Lethality=0;
printf("What is the Lethality of %s?\t(Answer in percentage. Sample:90 OR 12, etc)\n",Dissarray.Disease);
if (scanf("%d", &Dissarray.Lethality)!= 1)
{
printf("This is not an appropriate number. Please enter appropriately.\n");
fflush(stdin);
scanf("%d", &Dissarray.Lethality);
}
fprintf(fptr,"Lethality: %d\n",Dissarray.Lethality);
printf("\n");
fflush(stdin);
printf("How is %s acquired. (Sample: Contagious Disease, STI, Hereditary)\n",Dissarray.Disease);
gets(Dissarray.ContagionFactor);
fprintf(fptr,"Contagion factor: %s\n",Dissarray.ContagionFactor);
printf("\n");
printf("How is %s Transmitted?\t\t(Sample: Airborne, Touch, Sex, Sneezing, etc.)\n",Dissarray.Disease);
gets(Dissarray.Spread);
fprintf(fptr,"Spread: %s\n",Dissarray.Spread);
printf("\n");
fflush(stdin);
Dissarray.Fatalities=0;
printf("On a yearly basis. What is the average Fatality count brought by %s?\t\t(How many have died to this disease? Sample:100000)\n",Dissarray.Disease);
if(scanf("%d", &Dissarray.Fatalities)!= 1)
{
printf("This is not an appropriate number. Please enter appropriately.\n");
fflush(stdin);
scanf("%d", &Dissarray.Fatalities);
}
fprintf(fptr,"Fatalities: %d\n",Dissarray.Fatalities);
printf("\n");
fflush(stdin);
printf("Has %s been known to evolve under any conditions?\n",Dissarray.Disease);
printf("What is the Sensitivity?\t\t(Sample:Temperatures over 90 degrees OR None.)\n");
gets(Dissarray.Sensitivity);
fprintf(fptr,"Sensitivity: %s\n\n",Dissarray.Sensitivity);
printf("\n");
printf("This ends the entry of info into the file\n");
fclose(fptr);
}
to answer your question about line numbering:
regarding:
int diseasenum=1;
change to:
static int diseasenum=1;
Then, before exiting the function:
diseasenum++;

Function successfully writes to file but contents do not show

I have two functions that uses up a .dat file.
The first function adds a structure of a question and its answers to the file and the other is to view the questions in the file.
The addQues() function is called main inside a loop that inquires if the user wants to add more questions. The problem is when the addQues() function is called the second time and onward, it successfully writes the question to the file but when the viewQues() function is called, the questions are not shown. The size of the file also increases after each succeeding call of addques()
/* the structure is as follows */
typedef struct {
char question[256];
char choiceA[32];
char choiceB[32];
char choiceC[32];
char choiceD[32];
char ans;
int num;
}question;
/* function to add questions */
void addQues(){
FILE *fileptr;
question catcher, ques;
int x;
fileptr = fopen("Questions.dat", "a+");
if(fileptr != NULL){
catcher.num = 0;
while(fread(&catcher, sizeof(question), 1, fileptr)!= 0){}
printf("There are %d questions. Please type in the Question you would like to add.\n\nQuestion: ", catcher.num);
fflush(stdin);
scanf("%[^\n]%*c", &ques.question);
printf("Add four[4] choices to the question\n");
printf("\nChoice a.: ");
fflush(stdin);
scanf("%[^\n]%*c", &ques.choiceA);
printf("\nChoice b.: ");
fflush(stdin);
scanf("%[^\n]%*c", &ques.choiceB);
printf("\nChoice c.: ");
fflush(stdin);
scanf("%[^\n]%*c", &ques.choiceC);
printf("\nChoice d.: ");
fflush(stdin);
scanf("%[^\n]%*c", &ques.choiceD);
printf("\nType the letter of the correct answer of this question.\nAnswer: ");
fflush(stdin);
scanf("%c", &ques.ans);
ques.num = catcher.num+1;
printf("%s", ques.question); /* made this snippet to make sure that white spaces in my input were recorded */
getch();
if(fwrite(&ques, sizeof(question), 1,fileptr) == 1){
printf("File write was successful\n"); /* made this snippet to make sure if writing is successful. and it is successfull everytime */
}else{
printf("File write was unsuccessfull");
}
getch();
fclose(fileptr);
}else{
printf("File either not found or does not exist.");
}
}
/* code view the Questions in the file */
void viewQues(){
FILE *fp;
question ques;
fp = fopen("Questions.dat", "r");
if(fp != NULL){
while(fread(&ques, sizeof(question), 1, fp) != 0){
printf("[%d] %s\n", ques.num, ques.question);
}
fclose(fp);
}else{
printf("File is either not found or does not exist.");
}
}
I am somehow confused because it somethimes works fluidly, sometimes it doesn't.
This is only my 1st semester of taking up C-programming so I still have alot to learn.
I am also quite new to this website please do forgive me if I may have violated any required format.
EDIT:
The program requires the user to input a question, 4 choices, and it's correct answer.
in the addQues function before the program asks for input, it already notifies the user how many questions there are in the file.
example is
There are 0 question/s (this updates when a question is added). lease type in the Question you would like to add.
Question: //user types What is the capital of Philippines?
Enter Choice A: // user types 'Manila'
Enter Choice B: // user types 'Cebu'
Enter Choice C:// user types 'Davao'
Enter Choice C:// user types 'Palawan'
Enter the letter of the correct answer: // User types in 'a'
Expected output would be
[1] What is the capital of Philippines?
after the second call and onwards the output that it shows is still only
[1] What is the capital of Philippines?
I am sorry I do not know how to make the sample scenario different from the rest of the text.

How to accept space in string in C in the given code

Sorry about the previous code, I did not correctly interpreted the situation.
What's happening is the string is being stored with spaces but when i am trying to read it afterwards, The output flickers continuously (its like its reading it over and over again and printing it infinitely on itself.)
The records are stored in a file named record.dat
I am inserting image showing file contents stored after I input a new record in the file (Everything gets stored correctly here)
![These are the contents of record.dat right after i insert the new record]--> the image --> http://i.stack.imgur.com/YxGEd.png
and now when I try to look the details of this record on my application I get this.
![Output showing the record details but not entirely correct as " Finch" is missing] -- >> the image -- >> http://i.stack.imgur.com/zgmGY.png
and after this if i close the application and then start it again and try to read the previous data it shows this:
![This output is also flickering like before but now even the data is gone]-->> the image -->> http:// i.stack.imgur.com/ 4q0qb.png
(and just in case you are wondering -- the data is still there in the record.dat file -- all of it which i entered when i prevously created the record.)
I hope the problem is more clear now.....
void see(void)
{
FILE *ptr;
int test=0,rate;
int choice;
float time;
float intrst;
char c;
ptr=fopen("record.dat","r");
printf("Do you want to check by\n1.Account no\n2.Name\nEnter your choice:");
//Selection Choice with Validation
int once = 0;
do
{
if(once!=0)
{
printf("\nThe choice is invalid.\nEnter 1 for account number and 2 for name");
}
once = once+1;
} while ((scanf("%d%c", &choice, &c)!=2 || c!='\n') && clean_stdin());
if (choice==1)
{
//Account Number with Validation
once = 0;
do
{
if(once!=0)
{
printf("\nThe above account number is invalid.\nEnter an account number (numeric value only):");
}
else
{
printf("\nEnter an account number:");
}
once = once+1;
} while ((scanf("%d%c", &check.acc_no, &c)!=2 || c!='\n') && clean_stdin());
while (fscanf(ptr,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",&add.acc_no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.day,&add.deposit.year)!=EOF)
{
if(add.acc_no==check.acc_no)
{ system("cls");
test=1;
printf("\nAccount NO.:%d\nName:%s \nDOB:%d/%d/%d \nAge:%d \nAddress:%s \nCitizenship No:%s \nPhone number:%.0lf \nType Of Account:%s \nAmount deposited:$ %.2f \nDate Of Deposit:%d/%d/%d\n\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.citizenship,add.phone,
add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
if(strcmpi(add.acc_type,"fixed1")==0)
{
time=1.0;
rate=9;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $%.2f as interest on %d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+1);
}
else if(strcmpi(add.acc_type,"fixed2")==0)
{
time=2.0;
rate=11;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+2);
}
else if(strcmpi(add.acc_type,"fixed3")==0)
{
time=3.0;
rate=13;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+3);
}
else if(strcmpi(add.acc_type,"saving")==0)
{
time=(1.0/12.0);
rate=8;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d of every month",intrst,add.deposit.day);
}
else if(strcmpi(add.acc_type,"current")==0)
{
printf("\n\nYou will get no interest\a\a");
}
}
}
}
else if (choice==2)
{
printf("Enter the name:");
scanf("%s",&check.name);
while (fscanf(ptr,"%d %s %d/%d/%d %d %s %s %lf %s %f %d/%d/%d",&add.acc_no,add.name,&add.dob.month,&add.dob.day,&add.dob.year,&add.age,add.address,add.citizenship,&add.phone,add.acc_type,&add.amt,&add.deposit.month,&add.deposit.day,&add.deposit.year)!=EOF)
{
if(strcmpi(add.name,check.name)==0)
{ system("cls");
test=1;
printf("\nAccount No.:%d\nName:%s \nDOB:%d/%d/%d \nAge:%d \nAddress:%s \nCitizenship No:%s \nPhone number:%.0lf \nType Of Account:%s \nAmount deposited:$%.2f \nDate Of Deposit:%d/%d/%d\n\n",add.acc_no,add.name,add.dob.month,add.dob.day,add.dob.year,add.age,add.address,add.citizenship,add.phone,
add.acc_type,add.amt,add.deposit.month,add.deposit.day,add.deposit.year);
if(strcmpi(add.acc_type,"fixed1")==0)
{
time=1.0;
rate=9;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+1);
}
else if(strcmpi(add.acc_type,"fixed2")==0)
{
time=2.0;
rate=11;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+2);
}
else if(strcmpi(add.acc_type,"fixed3")==0)
{
time=3.0;
rate=13;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d/%d/%d",intrst,add.deposit.month,add.deposit.day,add.deposit.year+3);
}
else if(strcmpi(add.acc_type,"saving")==0)
{
time=(1.0/12.0);
rate=8;
intrst=interest(time,add.amt,rate);
printf("\n\nYou will get $.%.2f as interest on %d of every month",intrst,add.deposit.day);
}
else if(strcmpi(add.acc_type,"current")==0)
{
printf("\n\nYou will get no interest\a\a");
}
}
}
}
fclose(ptr);
if(test!=1)
{ system("cls");
printf("\nRecord not found!!\a\a\a");
see_invalid:
printf("\nEnter 0 to try again,1 to return to main menu and 2 to exit:");
scanf("%d",&main_exit);
system("cls");
if (main_exit==1)
menu();
else if (main_exit==2)
close();
else if(main_exit==0)
see();
else
{
system("cls");
printf("\nInvalid!\a");
goto see_invalid;}
}
else
{printf("\nEnter 1 to go to the main menu and 0 to exit:");
scanf("%d",&main_exit);}
if (main_exit==1)
{
system("cls");
menu();
}
else
{
system("cls");
close();
}
}
The recommended solution is not to use scanf since scanf is also vulnerable to buffer overflows. In any case, you are not actually doing any formatting with the scanf call. You can use fgets to read the input into a string and specify the maximum number of characters that you allow. Use something like the following:
printf("\nEnter the name: ");
fgets(add.name, MAX_NAME_SZ, stdin);
You can use the %[^...] format specifier to read spaces into a string. Here's an example program that hopefully gives you something to work from.
#include <stdio.h>
int main()
{
char const* line = "This is a string, 10";
char text[50];
int number;
// Read up to 49 characters not including ',' to text.
sscanf(line, "%49[^,], %d", text, &number);
printf("%s, %d\n", text, number);
return 0;
}
Output:
This is a string, 10
I think you should provide an example of a failing situation or at least clean up the code and only give us the buggy part.
I see a lot of printf use without \n at the end which I know can be a problem (which may aswell be completely out of the subject here).
Since I've never used scanf I can't tell where your error is but maybe if you reduced your code to the acquisition of the user's input (-> the scanf part) then an attempt to display it (-> the part where your string gets truncated as it meets the first space) we could easily help you fix that problem faster and would be nicer to read.

sort/search in stack [duplicate]

This question already has an answer here:
How to sort an array of structs in C?
(1 answer)
Closed 8 years ago.
I have created a stack system in C
It takes the First Name, Last name, and an employee number and the program runs fine.
#include<stdio.h>
#include<conio.h>
#define MAX 20
struct system
{
char first_name[15];
char surname[15];
}employee[20], temp;
int stack[MAX],front=-1,top=-1;
int i;
void push_element();
void pop_element();
void display_stack();
void display_first();
int main()
{
int option;
printf("STACK PROGRAM");
do
{
printf("\n\n 1.Push an element");
printf("\n 2.Pop an element");
printf("\n 3.Display stack");
printf("\n 4.Display first");
printf("\n 5.Display last");
printf("\n 6.Exit");
printf("\n Enter your choice: ");
scanf("%d",&option);
switch(option)
{
case 1: push_element();
break;
case 2: pop_element();
break;
case 3: display_stack();
break;
case 4: display_first();
break;
case 5: display_last();
break;
case 6: return 0;
}
}while(option!=6);
}
void push_element()
{
printf("\n Enter the first name: ");
scanf("%s",employee[i].first_name);
printf("\n Enter the Last name: ");
scanf("%s",employee[i].surname);
int num;
printf("\n Enter the employee number: ");
scanf("%d",&num);
i++;
if(front==0 && top==MAX-1)
printf("\n You have entered more than 20. Please delete a current input to make room. ");
else if(front==-1&&top==-1)
{
front=top=0;
stack[top]=num;
}
else if(top==MAX-1 && front!=0)
{
top=0;
stack[top]=num;
}
else
{
top++;
stack[top]=num;
}
}
void pop_element()
{
top--;
return top;
}
void display_stack()
{
int i;
if(front==-1)
printf("\n No Employees to display");
else
{
printf("\n List of employees:\n\n ");
printf(" Employee number First Name Surname\n\n");
for(i=front;i<=top;i++)
{
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
}
}
}
void display_first()
{
int i;
if(front==-1)
printf("\n No Employees to display");
else
{
printf("\n The first Employee in the stack is:\n\n ");
printf(" Employee number First Name Surname\n\n");
for(i=front;i<=top;i++)
break;
{
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
}
}
}
void display_last()
{
int i;
if(front==-1)
printf("\n No Employees to display");
else
{
printf("\n The last Employee in the stack is:\n \n");
printf(" Employee number First Name Surname\n\n");
for(i=top;i<=front;i++)
break;
{
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
}
}
}
I for the life of me cannot figure out how to sort the stack. I have tried other pieces of code and many different things, but none of them have came close to finding it
But I am wanting to sort it by alphabetical order. So not by entry time or Employee number, but by the First initial of the Surname
A search function is also required for this, and to be done by Employee number.
I have looked online, and the use of sorting and searching in a stack isn't a common thing, but I required to have it.
I am not good at C and I am fairly new to it. Any tips or things that may help me greatly would be appreciated. Also I apologies for any formatting errors, I'm fairly new to programming altogether and using software.
Your data structure doesn't directly record an employee number. You have the array stack which records the employee number, and the array employee which records names. You need to preserve the relationship stack[i] contains the employee number for employee[i] which means any sorting of the existing data structure has to sort two arrays in parallel. While it can be done, it is not the best way to fix the problems (and it is harder than it need be, and will require a custom sort function).
You should upgrade the data structure to include the employee number:
struct employee
{
int number;
char first_name[15];
char surname[15];
} employee[20];
Note that I've retagged the structure as struct employee (instead of struct system) since it seems more relevant to the content of the structure.
You can then use the qsort() function from the standard C library (declared in <stdlib.h>) and the techniques documented in the proposed duplicate (How to sort an array of structs in C?) to sort the data straight-forwardly. It is also easier to write your searching code.
You can also clean up the display code; you can have a single function that is passed an employee structure (or pointer to one). It will contain a single printf() statement that formats the data correctly. This saves you writing the same elaborate printf() code 3 times, making it easier to fix the formatting if (when) you need to do so. You can also avoid using tabs in the output (generally a good idea), leading to:
void print_employee(const struct employee *emp)
{
printf("%8d %-15s %-15s\n", emp->number, emp->first_name, emp->surname);
}
This will produce well aligned output unless your employee number grows to more than 8 digits (in which case, change the 8 to 10 or whatever). You can also generalize one step further if you wish, passing a FILE *fp argument to the function, and using fprintf(fp, "…", …) instead of printf().
You call the function:
print_employee(&employee[i]);
You might also consider a function to print the headings since you have that function call 3 times. Alternatively, you might just have a constant string at file scope that contains the correct headings which you use in 3 places. You could do that with the print_employee() function too; have a constant string at file scope that is the format you use.
Also, in your display_first() and display_last() functions, the loops are curious. You've written:
for(i=front;i<=top;i++)
break;
{
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
}
You should realize (on review) that this is equivalent to:
i = front;
printf(" %d \t\t %s \t %s\n", stack[i], employee[i].first_name, employee[i].surname);
(If front is larger than top, then i = front is the only part of the loop executed; otherwise, the break is executed; either way, after the loop, i == front.)

Program seems to freeze after executing a function?

I am doing a program that is a customer order application. Basically it is a database (like e-bay) where a customer must be registered in the system to buy a product. The problem I am currently having is when I come to modify a customer.
Basically when I run the program I have a menu. I choose customer and I have a sub-menu and I choose to modify the customer data. then it asks me for an id and the program checks whether it is valid or not. If the id number is valid it goes on to let you choose which criteria you want to modify. After the modification of that criteria it prints out ~~~ITEM EDITED~~~ and then it just like freeze. Nothing comes afterwards and I have to terminate the program myself.
This happens as well when an invalid id is entered. When this happens it prints out the main menu and when I enter a number to choose from the main menu nothing happens.
I tried solving it myself but cannot find the problem. I tried to use exit(0) instead of break; after the cases but same problem happened. Here under is the code of the modify function. Just to let you know that I have a header file with all the necessary information such as structure declaration.
modify_customer()
{
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
char another;
int flag = 0;
int choice;
char x[8];
FILE *pCust;
int size;
printf("\nENTER CUSTOMER ID NUMBER: ");
//fflush(stdout);
scanf("%s",x);
flag = checkcustomer(x);
if(flag==0)
{
pCust=fopen("customer.txt","r+b");
rewind(pCust);
while(fread(&cust,sizeof(cust),1,pCust))
{
if(strcmp(cust.id,x)==0)
{
printf("\nid ==> %s",cust.id);
printf("\nname ==> %s",cust.name);
printf("\nsurname ==> %s",cust.surname);
printf("\naddress ==> %s",cust.address);
printf("\nDO YOU WANT TO EDIT THIS REDORD [Y/N]: ");
scanf("%s", &another);
fflush(pCust);
if(another=='Y'|| another=='y')
{
printf("\n(1) EDIT ID NUMBER");
printf("\n(2) EDIT NAME");
printf("\n(3) EDIT SURNAME");
printf("\n(4) EDIT ADDRESS");
printf("\nenter choice (1) - (4) to edit: ");
//fflush(stdout);
scanf("%d",&choice);
switch(choice)
{
case 1 : printf("\nEDIT RECORD [ID]");
printf("\nenter new customerID:");
scanf("%s",cust.id);
size = sizeof(cust);
fseek(pCust,-size,SEEK_CUR);
fwrite(&cust,sizeof(cust),1,pCust);
break;
case 2 : printf("\nEDIT RECORD [NAME]");
printf("\nenter new name: ");
//fflush(stdout);
scanf("%s",cust.name);
size = sizeof(cust);
fseek(pCust,-size,SEEK_CUR);
fwrite(&cust,sizeof(cust),1,pCust);
break;
case 3 : printf("\nEDIT RECORD [SURNAME]");
printf("\nenter new surname: ");
//fflush(stdout);
scanf("%s",cust.surname);
size = sizeof(cust);
fseek(pCust,-size,SEEK_CUR);
fwrite(&cust,sizeof(cust),1,pCust);
break;
case 4 : printf("\nEDIT RECORD [ADDRESS]");
printf("\nenter new address: ");
//fflush(stdout);
scanf("%s",cust.address);
size = sizeof(cust);
fseek(pCust,-size,SEEK_CUR);
fwrite(&cust,sizeof(cust),1,pCust);
break;
}
printf("\n~~~ITEM EDITED~~~");
break;
}
else
{
printf("\nRECORDS ARE NOT MODIFIED");
customer_menu();
}
}
}
}
if(flag==1)
{
printf("\nITEM DOES NOT EXIST. TRY AGAIN");
main_menu();
}
fflush(stdout);
getch();
fclose(pCust);
return 0;
}

Resources