C function to add date adds gibberish - c

This program writes, edits and deletes tasks from a txt file. I'm having problems with my add task function (case (1)) in this situation. Here's a snippet of the code:
switch(choice)
{
case '1':
system("cls");
fseek(fp,0,SEEK_END);
another = 'y';
while(another == 'y')
{
printf("\nEnter Task_Name: ");
scanf("%s", &t.Task_Name);
printf("\nEnter Leader: ");
scanf("%s", &t.Leader);
printf("\nEnter L_Email: ");
scanf("%s", &t.L_Email);
printf("\nEnter Member: ");
scanf("%s", &t.Member);
printf("\nEnter Mem_Email: ");
scanf("%s", &t.Mem_Email);
printf("\nEnter Begin_date(dd/mm/yyyy): ");
scanf("%d/%d/%d", &dd,&mm,&yyyy);
printf("\nEnter End_date(dd/mm/yyyy): ");
scanf("%d/%d/%d", &dd,&mm,&yyyy);
fwrite(&t,recsize,1,fp);
printf("\nAdd another task(y/n) ");
fflush(stdin);
another = getche();
}
break;
However, when I attempt to add a date with the above code I get gibberish in return. For example, when I type 11/11/1111 as the start date and 11/11/1111 as the end date, I get 6421994 and 6422005 in return. The same numbers shows up when I input any other date too.
To keep things reproducible I will have to include the entire code;
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<process.h>
#include<dos.h>
int main()
{
FILE * fp, * ft;
char another, choice;
struct task
{
char Task_Name[50], Leader[50], L_Email[50], Member[50], Mem_Email[50], Begin_date[11], End_date[11];
};
struct task t;
int mm, dd, yyyy;
char TaskName[40];
long int recsize;
fp = fopen("task.txt","rb+");
if(fp == NULL)
{
fp = fopen("task.txt","wb+");
if(fp == NULL)
{
printf("Cannot open file");
exit(1);
}
}
recsize = sizeof(t);
while(1)
{
system("cls");
printf("\n\t **** Welcome to Personal System Management ****");
printf("\n\n\n\t\t\tMAIN MENU\n\t\t=====================\n\t\t[1] Add a new Task\n\t\t[2] View all Task\n\t\t[3] Update Task\n\t\t[4] Delete Task\n\t\t[5] Exit Program\n\t\t=================\n\t\t");
printf("Enter choice: ");
choice = getche();
switch(choice)
{
case '1':
system("cls");
fseek(fp,0,SEEK_END);
another = 'y';
while(another == 'y')
{
printf("\nEnter Task_Name: ");
scanf("%s", &t.Task_Name);
printf("\nEnter Leader: ");
scanf("%s", &t.Leader);
printf("\nEnter L_Email: ");
scanf("%s", &t.L_Email);
printf("\nEnter Member: ");
scanf("%s", &t.Member);
printf("\nEnter Mem_Email: ");
scanf("%s", &t.Mem_Email);
printf("\nEnter Begin_date(dd/mm/yyyy): ");
scanf("%d/%d/%d", &dd,&mm,&yyyy);
printf("\nEnter End_date(dd/mm/yyyy): ");
scanf("%d/%d/%d", &dd,&mm,&yyyy);
fwrite(&t,recsize,1,fp);
printf("\nAdd another task(y/n) ");
fflush(stdin);
another = getche();
}
break;
case '2':
system("cls");
rewind(fp);
printf("Task Name|Leader|Leader Email|Member|Member Email|Begin Date|End Date");
while(fread(&t,recsize,1,fp)==1)
{
printf("\n%s %s %s %s %s %d %d",t.Task_Name,t.Leader,t.L_Email,t.Member,t.Mem_Email,t.Begin_date,t.End_date);
}
getch();
break;
case '3':
system("cls");
another = 'y';
while(another == 'y')
{
printf("Enter the task name you want to update: ");
scanf("%s",TaskName);
rewind(fp);
while(fread(&t,recsize,1,fp)==1)
{
if(strcmp(t.Task_Name,TaskName) == 0)
{
printf("Enter new Member name: ");
scanf("%s",&t.Member);
printf("Enter new Member Email: ");
scanf("%s",&t.Mem_Email);
printf("Enter new End Date(dd/mm/yyyy): ");
scanf("%d/%d/%d",&dd,&mm,&yyyy);
fseek(fp,-recsize,SEEK_CUR);
fwrite(&t,recsize,1,fp);
break;
}
}
printf("\nUpdate another task(y/n)");
another = getche();
}
break;
case '4':
system("cls");
another = 'y';
while(another == 'y')
{
printf("Enter the task name you want to delete: ");
scanf("%s",TaskName);
ft = fopen("Temp.dat","wb");
rewind(fp);
while(fread(&t,recsize,1,fp) == 1)
{
if(strcmp(t.Task_Name,TaskName) != 0)
{
fwrite(&t,recsize,1,ft);
}
}
fclose(fp);
fclose(ft);
remove("task.txt");
rename("Temp.dat","task.txt");
fp = fopen("taxt.txt", "rb+");
printf("Delete another task(y/n)");
fflush(stdin);
another = getche();
}
break;
case '5':
fclose(fp);
exit(0);
}
}
return 0;
}

You're never copying the dates into the structure.
printf("\nEnter Begin_date(dd/mm/yyyy): ");
scanf("%d/%d/%d", &dd,&mm,&yyyy);
sprintf(t.Begin_date, "%02d/%02d/%04d", dd, mm, yyyy);
printf("\nEnter End_date(dd/mm/yyyy): ");
scanf("%d/%d/%d", &dd,&mm,&yyyy);
sprintf(t.End_date, "%02d/%02d/%04d", dd, mm, yyyy);
And since these are strings, you need to use %s when printing them, not %d.
printf("\n%s %s %s %s %s %s %s",t.Task_Name,t.Leader,t.L_Email,t.Member,t.Mem_Email,t.Begin_date,t.End_date);

Related

problem in appending multiple records in a file

I am having problem with appending more records to this file. It allows me add just one record but I cannot add more than one record. And cannot figure out what is going wrong with it?
void new_customer()
{
char ch;
int flag=0;
FILE *fp;
fp=fopen("DataFile.txt", "a+");
printf("Enter today's date (dd/mm/yyyy) : ");
scanf(" %d/%d/%d", &add.deposit.day, &add.deposit.month, &add.deposit.year);
printf("Enter Account Number : ");
fflush(stdin);
scanf("%ld", &check.account_number);
while(fscanf(fp, "%ld %s %s %s %s %s %d %d/%d/%d %d %d/%d/%d %c", &add.account_number, add.customer_name, add.father_name, add.address, add.Nationality, &add.p_number, &add.age, &add.dob.day, &add.dob.month, &add.dob.year, &add.amount, &add.deposit.day, &add.deposit.month, &add.deposit.year, &add.account_type)!=EOF)
{
if(check.account_number==add.account_number)
{
printf("Account number already taken. Please contact administrator.\nPress enter to continue.");
getch();
system("cls");
main();
}
}
add.account_number=check.account_number;
printf("Enter name : ");
fflush(stdin);
gets(add.customer_name);
printf("Enter Father's name : ");
fflush(stdin);
gets(add.father_name);
printf("Enter your age : ");
fflush(stdin);
scanf("%d", &add.age);
printf("Enter Date of birth (dd/mm/yyyy) : ");
scanf("%d/%d/%d", &add.dob.day, &add.dob.month, &add.dob.year);
printf("Enter Phone Number : ");
fflush(stdin);
gets(add.p_number);
printf("Enter Nationality : ");
fflush(stdin);
gets(add.Nationality);
printf("Enter Address : ");
fflush(stdin);
gets(add.address);
printf("Enter Account Type:\nPress S for Savings, \nPress C for Current, \nF for Fixed : ");
fflush(stdin);
scanf("%c",&add.account_type);
while(flag!=1)
{
if (add.account_type=='S'|| add.account_type=='s'||add.account_type=='C'||add.account_type=='c'||add.account_type=='F'||add.account_type=='f')
{
flag=1;
}
else
{
printf("\nWrong Input. Input Again : ");
fflush(stdin);
scanf("%c", &add.account_type);
flag=0;
}
}
printf("Deposit Amount : ");
fflush(stdin);
scanf("%d", &add.amount);
fprintf(fp, "%ld %s %s %s %s %s %d %d/%d/%d %d %d/%d/%d %c\n", add.account_number, add.customer_name, add.father_name, add.address, add.Nationality, add.p_number, add.age, add.dob.day, add.dob.month, add.dob.year, add.amount, add.deposit.day, add.deposit.month, add.deposit.year, add.account_type);
printf("\nAccount Created Successfully!!\n");
fclose(fp);
while(1)
{
printf("Return to Main Menu? Y/N : ");
fflush(stdin);
scanf("%c", &ch);
if(ch=='Y' || ch=='y')
{
system("cls");
main();
}
else if(ch=='N' || ch=='n')
{
exit(0);
}
else
{
printf("\nWrong input. Try Again!\n");
}
}
}
This is just a function to a big program. I am attaching just the part which includes file handling. If you want I can attach more code.
Here I am adding the main driver code
#include<windows.h>
#include<stdio.h>
#include<stdlib.h>
#include "E:\Projects\C Language\Bank-Management-System\File Containing Functions.c"
int menu(void);
int gotoxy(int x, int y)
{
COORD c;
c.X=x;
c.Y=y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}
int menu()
{
int i, a;
gotoxy(40,0);
printf("BANK MANAGEMENT SYSTEM\n");
gotoxy(43, 3);
printf(":: MAIN MENU ::\n");
gotoxy(40, 5);
printf("[1] Create a new account");
gotoxy(40, 6);
printf("[2] Update information of existing account");
gotoxy(40, 7);
printf("[3] Transactions");
gotoxy(40, 8);
printf("[4] Check details of existing account");
gotoxy(40, 9);
printf("[5] Remove existing account");
gotoxy(40, 10);
printf("[6] View Customer List");
gotoxy(40, 11);
printf("[7] Exit\n");
gotoxy(40, 15);
printf("Enter your choice : ");
scanf("%d", &a);
return a;
}
int main()
{
int choice;
choice=menu();
switch(choice)
{
case 1:
{
system("cls");
new_customer();
break;
}
case 3:
{
system("cls");
transaction();
break;
}
case 7 :
{
system("cls");
printf("Thank You for using our services!!");
exit(0);
}
default:
{
printf("Wrong Input!!\n");
getch();
system("cls");
menu();
}
}
getch();
return 0;
}
Link to see input : https://pasteboard.co/Jt3xWrP.jpg
Here is the file after first input : https://pasteboard.co/Jt3yYA9.jpg
Another input :https://pasteboard.co/Jt3yHSC.jpg (this is where it gets stuck forever and doesn't let me add another record)
Text stored inside file :
123 John Papa John 15, Yemen Road, Yemen USA 12345678 22 11/2/0 2000 27/9/2020 S
So to start with the file holds:
123 John Papa John 15, Yemen Road, Yemen USA 12345678 22 11/2/0 2000 27/9/2020 S
And you try to scan it with
fscanf(fp, "%ld %s %s %s %s %s %d %d/%d/%d %d %d/%d/%d %c"
That is:
1 number
5 strings
1 number
...
As you can see, the file doesn't match that.
123 John Papa John 15, Yemen Road, Yemen USA 12345678 22 11/2/0 2000 27/9/2020 S
^^^ ^^^ ^^^ ^^^ ^^^ ^^^ ^^^
ok ok ok ok ok ok Not ok, so stop here
The next fscanf will not match anything (it expects a number but the file has "Road") so nothing is read.
In other words, you are stuck in the while forever.
I'll recommend reading the file in a line by line manner using fgets.
Then you can (in principle) use sscanf afterwards. But notice that %s reads a single word and your code allow multiple words for a single entry! In other words - your file can't be parsed using %s.
So consider another file format. For instance, you could use 1 line for each item in a record. That will make parsing much easier.

C - 2 or more input validation inside while loop

I have a program in which it will ask for the user to record the student's name and grade. One of the functions I used is for the user to edit the record of the student. The code works but now what I'm scratching my head is how to implement a validation of input by the user. I tried searching but I can't find the exact answer I need.
I already implemented the first validation and it works, but now what I want for the second validation is to go back and ask again instead of breaking the loop.
Here's my code:
void update(struct data list[80], int num)
{
int count, tmp, rolltmp, option;
system("cls");
while(tmp < 1 || tmp > num)
{
printf("How many student records do you want to edit?: ");
scanf("%d",&tmp);
if(tmp >=1 && tmp <=num)
{
printf("\nEditing the Student Record: ");
for(count=0;count<tmp;count++)
{
printf("\nEnter Roll Number for Student #%d: ",count+1);
scanf("%d",&rolltmp);
if(rolltmp >=1 && rolltmp <= num)
{
fflush(stdin);
printf("\n[CHOICES]");
printf("\n[1] - Edit the Name\n[2] - Edit the Grade\n[3] - Edit Both Name and Grade");
printf("\nEnter Choice: ");
scanf("%d",&option);
switch(option)
{
case 1:
fflush(stdin);
printf("\nEnter New Name: ");
gets(list[rolltmp-1].name);
break;
case 2:
printf("\nEnter New Grade: ");
scanf("%d",&list[rolltmp-1].grades);
break;
case 3:
fflush(stdin);
printf("\nEnter New Name: ");
gets(list[rolltmp-1].name);
fflush(stdin);
printf("\nEnter New Grade: ");
scanf("%d",&list[rolltmp-1].grades);
break;
}
}
else
{
printf("\nNot Valid. Please enter from 1 to %d\n",num);
printf("Press any key to enter again...\n\n");
getch();
break;
}
}
}
else
{
printf("Not Valid. Please enter from 1 to %d",num);
getch();
break;
}
}
}

C Program GOTOXY on second screen

The first screen, gotoxy code is working. But in second screen. Nothing happens, like, it does not read the gotoxy code at all. Please enlighten me about the problem.
Here is the 1st screen :
Here is the 2nd screen :
Here is the code. I would love to learn more about gotoxy.
Thank you in advance.
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>
void gotoxy( int column, int line );
int main();
int addProduct();
struct product
{
int quantity, reorder, i, id;
char name[20];
float price;
};
COORD coord = {0, 0};
void gotoxy (int x, int y)
{
coord.X = x; coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
int main()
{
int choice;
gotoxy(17,5);
printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 SYZ INVENTORY PROGRAM \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");
gotoxy(17,18);
printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");
gotoxy(22,8);
printf("1. Add Product\n\n");
gotoxy(22,10);
printf("2. Display Product\n\n");
gotoxy(22,12);
printf("3. Search Product\n\n");
gotoxy(22,14);
printf("4. Reorder Level of Product\n\n");
gotoxy(22,16);
printf("5. Update Product\n\n");
gotoxy(22,20);
printf("Please Enter Your Choice : ");
scanf(" %d", &choice);
switch(choice)
{
case 1 : addProduct();
break;
case 2 : displayProduct();
break;
case 3 : searchProduct();
break;
case 4 : reorderProduct();
break;
case 5 : updateProduct();
break;
default : printf("Wrong input. Please try again.");
system("cls");
main();
}
return (0);
}
int addProduct()
{
FILE * fp;
int i=0;
struct product a;
system("cls");
char checker;
gotoxy(17,5);
printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2 SYZ INVENTORY PROGRAM \xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");
gotoxy(17,18);
printf("\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2\xB2");
do
{
fp = fopen("inventory.txt","a+t");
system("cls");
printf("Enter product ID : ");
scanf(" %d", &a.id);
printf("Enter product name : ");
scanf(" %s", a.name);
printf("Enter product quantity : ");
scanf(" %d", &a.quantity);
printf("Enter product price : ");
scanf(" %f", &a.price);
fprintf(fp, "%d %s %d %f\n\n", a.id, a.name, a.quantity, a.price);
printf("Record saved!\n\n");
fclose(fp);
printf("Do you want to enter new product? Y / N : ");
scanf(" %c", &checker);
checker = toupper(checker);
i++;
system("cls");
}
while(checker=='Y');
if(checker == 'N')
{
main();
}
else
{
do{
printf("Do you want to enter new product? Y / N : ");
scanf(" %c", &checker);
checker = toupper(checker);
}while(checker != 'Y' && checker != 'N');
if(checker == 'Y'){addProduct();}
if(checker == 'N'){
system("cls");
main();}
}
return(0);
}

Why does it keep crashing?

Any idea on when I choose to add a client and as soon as I enter in a client ID the program crashes for that entry?
#include <stdio.h>
#include <stdlib.h>
struct client
{
int clID;
char cname;
char caddress;
char cemail;
int cfees;
int ceID;
char cename;
}typedef client;
struct employee
{
int empID;
char ename;
double erate;
double ehours;
double esalary;
int ecID;
}typedef employee;
void mainMenu();
void clientMenu();
void empMenu();
void getClient(client* pcli);
void getEmp(employee* pemp);
void payroll(employee* pemp);
void dispPay(employee* pemp);
void dispClient(client* pcli);
void dispEmployee(employee* pemp);
int main()
{
client cli[100];
client* pcli = &cli[0];
employee emp[20];
employee* pemp = &emp[0];
int answer = -1;
int mchoice;
int cchoice;
int echoice;
int ccount;
int ecount;
int input[9];
int* psearchclientID;
int i;
printf("Do you wish to start the program? 1 for yes 2 for no: ");
scanf("%d", &answer);
if(answer ==1)
{
while(mchoice != 3)
{
mainMenu();
scanf("%d", &mchoice);
switch(mchoice)
{
case 1: while(cchoice != 3)
{
clientMenu();
scanf("%d", &cchoice);
switch(cchoice)
{
case 1: getClient(pcli + i);
ccount++;
break;
case 2: printf("Enter the client ID to search for: ");
psearchclientID = fgets(input, 9, stdin);
strtok(input, "\n");
for(i = 0; i < 1; i++)
{
if(strcmpi(psearchclientID, (pcli->clID + i)) == 0)
printf("Client found at position %d\n", i);
else
printf("Client not found!");
}//end for
break;
}//end client switch
}//end client while
cchoice = 0;
break;
case 2: while(echoice != 4)
{
empMenu();
scanf("%d", &echoice);
switch(echoice)
{
case 1: getEmp(pemp + i);
ecount++;
break;
case 2: payroll(pemp + i);
dispPay(pemp + i);
break;
case 3:
break;
}//end emp switch
}//end emp while
echoice =0;
break;
}//end switch
}//end main while
}//end if
else if(answer ==2)
{
printf("Goodbye!");
exit(0);
}
return 0;
}//end main
void mainMenu()
{
printf("1-Client Menu\n"
"2-Employee Menu\n"
"3-Quit\n");
printf("Enter a choice from the menu: ");
}//end mainMenu
void clientMenu()
{
printf("1-Add a client\n"
"2-Search client\n"
"3-Go Back to Main Menu\n");
printf("Enter a choice from the menu: ");
}//end clientMenu
void empMenu()
{
printf("1-Add an Employee\n"
"2-Process an Employee(payroll)\n"
"3-Search Employee\n"
"4-Go Back to Main Menu\n");
printf("Enter a choice from the menu: ");
}//end empMenu
This is specifically the code for entering in the client info
void getClient(client* pcli)
{
printf("Enter client ID: ");
scanf("%d", &pcli->clID);
printf("Enter client name: ");
scanf("%s", &pcli->cname);
printf("Enter client address: ");
scanf("%s", &pcli->caddress);
printf("Enter client email: ");
scanf("%s", &pcli->cemail);
printf("Enter monthly service fees:" );
scanf("%d", &pcli->cfees);
}//end getClient
void getEmp(employee* pemp)
{
printf("Enter employee ID: ");
scanf("%d", &pemp->empID);
printf("Enter employee name: ");
scanf("%s", &pemp->ename);
printf("Enter employee hourly rate: ");
scanf("%lf", &pemp->erate);
printf("Enter employee hours worked: ");
scanf("%lf", &pemp->ehours);
}//end getEmp
void payroll(employee* pemp)
{
pemp->esalary = pemp->erate * pemp->ehours;
}//end payroll
void dispPay(employee* pemp)
{
printf("Employee ID %d\nEmployee Salary: %2.2f\n", pemp->empID, pemp->esalary);
}//end dispPay
This is where the information would be displayed
void dispClient(client* pcli)
{
printf("Client ID: %d\n Name: %s\n Address: %s\n Email: %s\n Monthly fees: %d\n Employee assigned: %d\n Employee name: %s\n", pcli->clID, pcli->cname, pcli->caddress, pcli->cemail, pcli->cfees, pcli->ceID, pcli->cename);
}//end dispClient
void dispEmployee(employee* pemp)
{
printf("Employee ID: %d\n Name: %s\n Hourly Rate: %2.2f\n Hours worked: %2.2f\n Salary: %2.2f\n Client(s) assigned: %s\n", pemp->empID, pemp->ename, pemp->erate, pemp->ehours, pemp->esalary, pemp->ecID);
}//end dispEmp
You don't include & (address) operator for %s (strings) while reading. For example, in function getClient, use
printf("Enter employee name: ");
scanf("%s", pemp->ename);
This is one of the problems in your program.
Your clientMenu switch statement to add a client calls:
case 1: getClient(pcli + i);
It is possible to be in that routine where i is uninitialized, so it could be anything, and very likely beyond the bounds of your 100 element array. In that case getClient will very likely be operating in memory it does not own, making your program liable to crash.
It's possible there's more than that issue at play, as well. As others have stated, more information about the crash would help.

scanf is skipped even if using fflush

I have a scanf that doesn't accept input. The value is automatically zero, even if the variable wasn't initialized. The scanf is skipped:
printf("\nEnter the number of the student to be dropped: ");
fflush(stdin);
scanf(" %d ",&choice);
printf("choice is %d", choice);
When the program is run, it immediately displays "choice is 0".
The snippet above is taken from the drop() function in this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student{
char name[50];
char* course;
};
main()
{
char repeat;
do{
system("cls");
int mainchoice;
printf("Student Enrollment System");
printf("\n");
printf("\n");
printf("1. View\n");
printf("2. Enroll\n");
printf("3. Drop enrollment\n");
printf("Select choice: ");
fflush(stdin);
scanf("%d",&mainchoice);
system("cls");
switch(mainchoice){
case 1:
view();
break;
case 2:
enroll();
break;
case 3:
drop();
break;
default:
printf("Please enter a valid number.");
getch();
fflush(stdin);
break;
}
printf("\nWould you like to make another transaction? [Y/N]: ");
fflush(stdin);
scanf("%c",&repeat);
}while(repeat=='Y'||repeat=='y');
}
view(){
int ctr = count();
printf("Enrolled Students:\n\n");
system("type records.txt");
printf("\n\nNumber of students enrolled: %d", ctr);
getch();
fflush(stdin);
}
enroll(){
int choice;
char validate;
printf("1. Information Technology\n");
printf("2. Computer Science\n");
printf("3. Computer Engineering\n");
printf("4. Information Systems\n");
struct student news;
printf("Name: ");
fflush(stdin);
gets(news.name);
printf("Course Number: ");
fflush(stdin);
scanf("%d", &choice);
switch(choice){
case 1:
news.course = "BSIT";
break;
case 2:
news.course= "BSCS";
break;
case 3:
news.course = "BSCpE";
break;
case 4:
news.course = "BSIS";
break;
default:
printf("Please enter a valid number\n");
break;
}
printf("Enroll %s to %s? [Y/N]:",news.name,news.course);
fflush(stdin);
scanf("%c", &choice);
if(choice=='Y' || choice=='y')
{
FILE * records;
records = fopen("records.txt", "a+");
fprintf(records, "%s, %s\n",news.name,news.course);
fclose(records);
printf("%s has been enrolled to %s\n",news.name, news.course);
}
else
{
printf("You have chosen to cancel your transaction");
}
}
drop(){
printf("Drop Student:\n\n");
int ctr = 0;
int choice; //which student to delete
char c;
FILE * record; // original records.txt
FILE* repo; //temporary data storage
record = freopen("records.txt", "r", stdin);
while((c = fgetchar())!=EOF){
if(c == '\n'){
}
else{
ctr=ctr+1;
printf("%d. ", ctr);
while(1){
printf("%c",c);
c= fgetchar();
if(c=='\n'){
printf("%c",c);
break;
}
}
}
}
fclose(record);
fflush(stdin);
fflush(stdin);
printf("\nEnter the number of the student to be dropped: ");
fflush(stdin);
scanf(" %d ",&choice);
getch();
getch();
fflush(stdin);
ctr = 1;
fflush(stdin);
repo = fopen("temp.txt","w");
record = freopen("records.txt","r",stdin);
while((c = getchar()) != EOF){
if(c == '\n'){
}
else{
while(ctr!=choice){
fprintf(repo,"%c",c);
c= fgetchar();
if(c=='\n'){
fprintf(repo,"%c",c);
ctr = ctr + 1;
break;
}
}
}
}
fclose(record);
fclose(repo);
getch();
}
//counts the number of rows in the record
int count(){
int ctr=0;
char c;
FILE * records;
records = freopen("records.txt","r", stdin);
if(records!=NULL){
while((c=fgetchar()) !=EOF){
if(c=='\n'){
ctr = ctr+1;
}
}
}
fclose(records);
return ctr;
}
Doing fflush doesn't seem to help. Any ideas?
The behavior of fflush is not defined for input streams; fflush(stdin) is a coding error, and you should remove those calls from your code.
When scanning for individual characters, add a blank space before the %c conversion specifier; this will tell scanf to skip any leading whitespace and read the next non-whitespace character:
scanf(" %c", &choice);
The %d and %s conversion specifiers will skip over any leading whitespace.
Edit
Implicit typing is no longer supported as of C99, and it's a bad habit to get into. Explicitly type your functions, and use void as the parameter list to specify that they take no arguments:
main() => int main(void)
view() => void view(void) // void since it isn't returning a value
drop() => void drop(void)
etc.
Similarly, gets was deprecated in C99 and is gone completely as of the 2011 standard. Using it will introduce a point of failure / major security hole in your program. Use fgets instead.

Resources